我尝试使用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匹配。在
这应该能让你开始。在
您的XPath表达式与任何内容都不匹配,因为您尝试擦除的HTML页面严重损坏。FF(或任何其他web浏览器)会在移动中修复页面,然后再显示它。这将导致添加HTML标记,而这些标记在原始文档中不存在。在
下面的代码包含一个XPath表达式,它很可能会为您指明正确的方向。在
执行时,将打印以下内容:
^{pr2}$小贴士:每当你试图抓取一个网页,但事情没有如预期的那样工作,下载HTML并保存到一个文件中。在这种情况下,例如:
^{3}$然后看看保存的HTML。这将使您了解DOM的外观。在
下面的代码应该可以完成这项工作,也就是说,当使用具有匹配XPath表达式的其他站点时,它可以工作。racenet站点没有提供有效的HTML,这很可能是代码失败的原因。这可以通过使用W3C联机验证器进行验证:https://validator.w3.org
相关问题 更多 >
编程相关推荐