从 python 中的 xpath 条目获取文本时遇到问题
我在网站
http://www.baseball- Reference.com/players/event_hr.cgi?id=bondsba01&t=b
并尝试从表中抓取数据。当我从一个条目中拉出 xpath 时,投手说 “Terry Mulholland”,我检索到了这个:
pitchers = site.xpath("/html/body/div[2]/div[2]/div[6]/table/tbody/tr/td[3]/table/tbody/tr[2]/td/a)
当我尝试在打印机中打印投手的 pitcher[0].text
时,我得到的是 []
而不是 text
,知道为什么吗?
I am on the website
http://www.baseball-reference.com/players/event_hr.cgi?id=bondsba01&t=b
and trying to scrape the data from the tables. When I pull the xpath from one entry, say the pitcher
"Terry Mulholland," I retrieve this:
pitchers = site.xpath("/html/body/div[2]/div[2]/div[6]/table/tbody/tr/td[3]/table/tbody/tr[2]/td/a)
When I try to print pitcher[0].text
for pitcher in printers, I get []
rather than the text
, Any idea why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,原始源中不存在最后一个
tbody
。如果您通过某些浏览器获取该 xpath,请记住浏览器可以猜测并添加缺失的元素以使 html 有效。删除最后一个
tbody
即可解决该问题。但我需要补充一点,您使用的 xpath 表达式非常脆弱。在某个方便的位置添加了一个
div
,现在您的脚本已损坏。如果可能,尝试找到更好的引用,例如指向您预期位置的id
或class
。The problem is, last
tbody
doesn't exist in the original source. If you get that xpath via some browser, keep in mind that browsers can guess and add missing elements to make html valid.Removing the last
tbody
resolves the problem.But I need to add that, the xpath expression you are using is pretty fragile. One
div
added in some convenient place and now you have a broken script. If possible, try to find better references likeid
orclass
that points to your expected location.