2017-12-28 6 views
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)というテキストの後に最初のテーブルが見つかります。 https://www.iaaf.org/competitions/iaaf-world-championships/iaaf-world-championships-london-2017-5151/medaltable

enter image description here

答えて

-1

あなたは、XPathのことで、以下のようなものをfollowingを使用することができますか、私は「メダルTABLE」(別のURL)を読み取り、テキストの後の最初のテーブルを見つける必要があります。

relative_string = "Split times" 

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

おかげさまで、ありがとうございます。それは 'lxml.etree.XPathEvalError:無効な式'を返します。上記の構文をテストしましたか? – Dongs14173

+0

申し訳ありません、私はこれを使用しました、 'ResultsTable = ResultsTree.xpath(( "" * * [text()[normalize-space()、 "SPLIT TIMES")]]/following :: table " "")) 'を返しますが、空の値を返します – Dongs14173

+0

ページをチェックすると、分割時間は「分割時間」となります。 – 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

関連する問題

 関連する問題