2017-12-28 28 views
1

주어진 후 1 테이블을 찾기 위해 상대 XPath를 사용합니다. 여기 https://www.iaaf.org/competitions/iaaf-world-championships/iaaf-world-championships-london-2017-5151/results/men/10000-metres/final/result을 발견하고 아래 그림에 표시되는 'SPLIT TIMES'테이블에서 연마 것이다는 XPath를 찾기 위해 노력하고, 나는 나 텍스트 '<strong>SPLIT TIMES</strong>'후 <strong>첫</strong> 테이블을 가져올 수 상대 (절대하지 않음) XPath는을 찾기 위해 노력하고 텍스트

from lxml import html 
import requests 

ResultsPage = requests.get('https://www.iaaf.org/competitions/iaaf-world-championships/iaaf-world-championships-london-2017-5151/results/men/10000-metres/final/result') 
ResultsTree = html.fromstring(ResultsPage.content) 
ResultsTable = ResultsTree.xpath(("""//*[text()[contains(normalize-space(), "SPLIT TIMES")]]""")) 

print ResultsTable 

: 이것은 내 코드입니다.

Xpath가 가능한 한 다양 할 수 있다면 감사하게 생각합니다. 예를 들어, 요구 사항이 변경되어 '10, 000 METERS MEN '(위와 동일한 URL)이라는 텍스트 뒤에 첫 번째 테이블을 찾을 수 있습니다. 또는, 나는 '메달 TABLE'(다른 URL)를 읽고 텍스트 후 첫 번째 테이블을 찾을 필요가 있습니다 : 아래처럼 XPath는에 의해 뭔가를 following을 사용할 수 있습니다 https://www.iaaf.org/competitions/iaaf-world-championships/iaaf-world-championships-london-2017-5151/medaltable

enter image description here

답변

-1

. 코드에 문제가 있습니다

relative_string = "Split times" 

ResultsTable = ResultsTree.xpath("//*[text()[contains(normalize-space(), '"+relative_string+"')]]/following::table") 
+0

안녕하세요. 'lxml.etree.XPathEvalError : 잘못된 표현식'을 반환합니다. 위 구문을 테스트 했습니까? – Dongs14173

+0

죄송합니다, 지금 사용했습니다 'ResultsTable = ResultsTree.xpath (("normalize-space(),"SPLIT TIMES ")]]/following :: table" "")) '을 반환하지만 빈 값을 반환합니다. – Dongs14173

+0

페이지를 확인하면 SPLIT TIMES의 철자가 "Split times"입니다. – johnII

1

당신이 긁어하려고하는 그 웹 사이트가 요청을 (다른 대답에 지적 사용자 에이전트 헤더에없는) 거부하는 보호 기능을 사용하기 때문에 :

The request could not be satisfied. Request blocked. Generated by cloudfront (CloudFront)

이 라이브러리를 사용하여 이것을 우회 할 수있었습니다 : cloudflare-scrape.

당신은 핍 사용하여 설치할 수 있습니다 : 문서에 설명 된대로 여기

pip install cfscrape 

그리고 당신이 달성하려고하는 무엇에 대한 작업 XPath를 가진 코드는 트릭은 "다음"도끼를 사용하는 것이 었습니다 : https://www.w3.org/TR/xpath/#axes.

import cfscrape 
from lxml import html 

scraper = cfscrape.create_scraper() 
page = scraper.get('https://www.iaaf.org/competitions/iaaf-world-championships/iaaf-world-championships-london-2017-5151/results/men/10000-metres/final/result') 
tree = html.fromstring(page.content) 
table = tree.xpath(".//h2[contains(text(), 'Split times')][1]/following::table[1]") 
+0

많은 감사합니다! :-) – Dongs14173

+0

https://stackoverflow.com/help/someone-answers – Isma