【问题标题】:Why does BS4 (from BeautifulSoup) return only [ ] when using the .select()?为什么 BS4(来自 BeautifulSoup)在使用 .select() 时只返回 [ ]?
【发布时间】:2020-03-18 10:49:18
【问题描述】:

以下代码仅返回空括号。我看过这篇帖子Why does bs4 return tags and then an empty list to this find_all() method?,但它有所不同,因为我没有使用find_all(),而是.select()。请注意,我将“nth-child”更改为“nth-of-type”以避免错误。

    import bs4
    import requests
    res = requests.get('http://www.sharkresearchcommittee.com/pacific_coast_shark_news.htm')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
soup.select('body > div > div:nth-of-type(2) > center > table > tbody > tr:nth-of-type(1) >td:nth-of-type(2) > p:nth-of-type(8) > strong:nth-of-type(1) > font')

输出为 [ ]

【问题讨论】:

  • ...因为有 0 个匹配项?
  • 请注意,tbody 元素实际上并不存在于标记中,它们是由浏览器和解析器添加的,例如 html5lib(与 html.parser 不同)。
  • @Blender - 感谢您的回复。我取出了 tbody 仍然得到相同的输出

标签: python beautifulsoup jupyter-notebook


【解决方案1】:

如果您告诉我们您要匹配的内容可能会更有意义。因为您没有匹配的原因显然是因为您的选择没有任何匹配。

根据您选择的其余部分,我猜您此时处于错误的 div 中:

body > div > div:nth-of-type(2)

那个 DIV 包含这个文本:

本网站包含的材料作为公共服务共享 并进一步推动鲨鱼研究委员会的科学目标。 本网站上的所有文字和图像均为本网站的专有财产 鲨鱼研究委员会....

我猜你想从那里进入 div,这就是你可能想要的选择器:

soup.select('body > div > div > center > table > tr > td:nth-of-type(2) > p:nth-of-type(8) > strong > font')

以上内容将为您提供:

[<font size="4">Ventura </font>, <font size="4">  </font>]

没有深入研究它,但我相信有比你用来获得相同东西的更好的选择选择。但以上内容可能会让你得到你想要的。

完整代码:

import bs4
import requests
res = requests.get('http://www.sharkresearchcommittee.com/pacific_coast_shark_news.htm')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
print(repr(soup.select('body > div > div > center > table > tr > td:nth-of-type(2) > p:nth-of-type(8) > strong > font')))

跑步:

markh@mob:~/stackoverflow/51256960$ python bs1.py 
[<font size="4">Ventura </font>, <font size="4">  </font>]

【讨论】:

  • @clockwatcher 。我的印象是我正在复制正确的 CSS 选择器,因为我右键单击了我想从网页中选择的文本(文本是威尼斯......我只想要鲨鱼瞄准的位置)。我尝试了您的代码,它返回了相同的 []。感谢您的意见。
  • @pes04 -- 您一定没有正确复制我的选择器或以某种方式对其进行编辑。我用完整的代码更新了评论。
  • 你说得对,我错了@clockwatcher,它返回了 Ventura 线路。谢谢!!
【解决方案2】:

这意味着它找不到任何匹配项。

要么没有这样的标签,但如果你确定有,然后尝试使用html5liblxml parsers

我希望这会有所帮助。

【讨论】:

    【解决方案3】:

    为避免使用.select出现不匹配的错误,您可以执行以下操作:

    打开检查元素或开发者工具

    • Chrome Ctrl + Shift + IF12 或右键单击检查元素
    • Opera Ctrl + Shift + C 或右键检查元素
    • Safari Ctrl + Shift + I
    • Firefoz Ctrl + Shift + IF12

    请注意,对于 MAC,您应该使用 Ctrl + Shift + I

    开发者工具打开后,检查您想要定位的元素。

    通常元素会有一个 class 或 id 关键字(希望如此)

    抓取id或者class,如下图。

    要获取 id,请确保您的代码如下所示:soup.select('#CompanyInfo') 要获取 class,请确保您的代码如下所示soup.select('.CompanyInfo')

    注意:您只能使用soup.select('.CompanyInfo')[0].getText() 打印文本 不要忘记添加索引,因为 select 返回一个列表。

    编码愉快!

    【讨论】:

      【解决方案4】:

      tbody 是我的问题。

      我是通过一层一层添加选择器级别找到的,并检测到它会产生一个空列表。

      【讨论】:

        猜你喜欢
        • 2021-03-11
        • 2020-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-30
        • 2016-06-09
        • 1970-01-01
        • 2011-03-30
        相关资源
        最近更新 更多