从 python 中的 xpath 条目获取文本时遇到问题

发布于 2025-01-04 21:20:30 字数 505 浏览 3 评论 0原文

我在网站

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

所有深爱都是秘密 2025-01-11 21:20:30

问题是,原始源中不存在最后一个tbody。如果您通过某些浏览器获取该 xpath,请记住浏览器可以猜测并添加缺失的元素以使 html 有效。

删除最后一个 tbody 即可解决该问题。

In : import lxml.html as html

In : site = html.parse("http://www.baseball-reference.com/players/event_hr.cgi?id=bondsba01&t=b")

In : pitchers = site.xpath("/html/body/div[2]/div[2]/div[6]/table/tbody/tr/td[3]/table/tr[2]/td/a")

In : pitchers[0].text
Out: 'Terry Mulholland'

但我需要补充一点,您使用的 xpath 表达式非常脆弱。在某个方便的位置添加了一个 div,现在您的脚本已损坏。如果可能,尝试找到更好的引用,例如指向您预期位置的 idclass

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.

In : import lxml.html as html

In : site = html.parse("http://www.baseball-reference.com/players/event_hr.cgi?id=bondsba01&t=b")

In : pitchers = site.xpath("/html/body/div[2]/div[2]/div[6]/table/tbody/tr/td[3]/table/tr[2]/td/a")

In : pitchers[0].text
Out: 'Terry Mulholland'

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 like id or class that points to your expected location.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文