虽然已经使用/text(),但无法使用Xpath获取文本

2024-09-29 23:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用XPath从here中获取数据,尽管我使用inspect复制路径并在末尾添加/text(),但返回的是空列表,而不是最后span标记之间的文本的["Class 5"]。在

import requests
from lxml import html

sample_page = requests.get("https://www.racenet.com.au/horse-racing-results/happy-valley/2016-11-16")
tree = html.fromstring(sample_page.content)
r1class = tree.xpath('//*[@id="resultsListContainer"]/div[3]/table/tbody/tr[1]/td/span[1]/text()')

print(r1class)

我的目标元素是race1(类5)的类,结构与我使用的XPath匹配。在


Tags: sampletextimport路径tree列表herehtml
3条回答

这应该能让你开始。在

import requests
from lxml.etree import HTML

sample_page = requests.get("https://www.racenet.com.au/horse-racing-results/happy-valley/2016-11-16").content
tree = HTML(sample_page)
races = tree.xpath('//table[@class="tblLatestHorseResults"]')
for race in races:
    rows = race.xpath('.//tr')
    for row in rows:
        row_text_as_list = [i.xpath('string()').replace(u'\xa0', u'') for i in row.xpath('.//td') if i is not None]

您的XPath表达式与任何内容都不匹配,因为您尝试擦除的HTML页面严重损坏。FF(或任何其他web浏览器)会在移动中修复页面,然后再显示它。这将导致添加HTML标记,而这些标记在原始文档中不存在。在

下面的代码包含一个XPath表达式,它很可能会为您指明正确的方向。在

import requests
from lxml import html, etree
sample_page = requests.get("https://www.racenet.com.au/horse-racing-results/happy-valley/2016-11-16")
tree = html.fromstring(sample_page.content)
nodes = tree.xpath("//*[@id='resultsListContainer']/div/table[@class='tblLatestHorseResults']/tr[@class='raceDetails']/td/span[1]")
for node in nodes:
    print etree.tostring(node)

执行时,将打印以下内容:

^{pr2}$

小贴士:每当你试图抓取一个网页,但事情没有如预期的那样工作,下载HTML并保存到一个文件中。在这种情况下,例如:

^{3}$

然后看看保存的HTML。这将使您了解DOM的外观。在

下面的代码应该可以完成这项工作,也就是说,当使用具有匹配XPath表达式的其他站点时,它可以工作。racenet站点没有提供有效的HTML,这很可能是代码失败的原因。这可以通过使用W3C联机验证器进行验证:https://validator.w3.org

import lxml.html

html = lxml.html.parse('https://www.racenet.com.au/horse-racing-results/happy-valley/2016-11-16')
r1class = html.xpath('//*[@id="resultsListContainer"]/div[3]/table/tbody/tr[1]/td/span[1]/text()')[0]
print(r1class)

相关问题 更多 >

    热门问题