【问题标题】:python bs4 not finding divpython bs4找不到div
【发布时间】:2018-05-11 14:24:35
【问题描述】:

我正在尝试抓取https://www.edsurge.com/product-reviews/curriculum-products/math

当我这样做时:

site = 'https://www.edsurge.com/product-reviews/curriculum-products/math'
soup = bs.BeautifulSoup(urlopen(site),"html5lib")
print soup

我可以找到我要找的 div <div class="browse-main p1">

但是,当我尝试使用以下方法找到它时:

for div in soup.findall('div',class_='browse-main p1'):
        print div

我收到此错误(可能意味着它找不到 div)。

for div in soup.findall('div',class_='browse-main p1'):
TypeError: 'NoneType' object is not callable

我也尝试使用soup.findall('div'),但找不到任何东西。 我知道我可以使用硒,但如果没有必要,我宁愿不用。我觉得奇怪的是,当我打印汤时,div 存在。

有人知道怎么回事吗? 谢谢

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    findall 为 None,因此不可调用。

    试试:

    for div in soup.findAll('div',class_='browse-main p1'):
    

    【讨论】:

    • 扩展答案:soup 实现了 __getattr__ 钩子(用于动态属性解析),但没有正确引发未知方法的 AttributeError - 相反它返回 None。由于方法名称为findAll(不是findall),soup.findall 实际上 evals 为None,它(当然)不可调用,因此出现错误消息。
    • @brunodesthuilliers,我已将您的评论纳入社区答案(如下),因为它是重要信息。随意编辑它并添加一些点(如果有的话)。
    【解决方案2】:

    正如@brunothe comment 中提到的:

    soup 实现了__getattr__ 钩子(用于动态属性解析),但没有为未知方法正确引发AttributeError - 而是返回None。由于方法名为 findAll(不是 findall),soup.findall 实际上 evals 为 None,它(当然)不可调用,因此出现错误消息。

    另外,请注意 findAll() 是 bs3 语法。 bs4 的语法是find_all()

    所以,你应该使用

    soup.find_all('div',class_='browse-main p1')
    

    而不是

    soup.findall('div',class_='browse-main p1')
    

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 2017-12-21
      • 2018-06-05
      • 2019-09-29
      • 2020-06-22
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多