【问题标题】:Python None check seems to fail using BeautifulSoupPython None 检查似乎使用 BeautifulSoup 失败
【发布时间】:2014-09-27 20:33:00
【问题描述】:

我看过类似的帖子,与我的情况很接近,但我的结果似乎出乎意料。

import BeautifulSoup
import re

soup = BeautifulSoup.BeautifulSoup(<html page of interest>)
if (soup.find_all("td", attrs= {"class": "FilterElement"}, text= re.compile("HERE IS TEXT I AM LOOKING FOR")) is None):
    print('There was no entry')
else:
    print(soup.find("td", attrs= {"class": "FilterElement"}, text= re.compile("HERE IS THE TEXT I AM LOOKING FOR")))

我显然过滤掉了实际的 HTML 页面,以及正则表达式中的文本。其余的和写的完全一样。我收到以下错误:

Traceback (most recent call last):
  File "/Users/appa/src/workspace/web_forms/WebForms/src/root/queryForms.py", line 51, in <module>
    LoopThroughDays(form, id, trailer)
  File "/Users/appa/src/workspace/web_forms/WebForms/src/root/queryForms.py", line 33, in LoopThroughDays
    if (soup.find_all("td", attrs= {"class": "FilterElement"}, text= re.compile("HERE IS THE TEXT I AM LOOKING FOR")) is None):
TypeError: 'NoneType' object is not callable

我了解有时会丢失文本。但我认为我设置if 语句的方式能够准确地捕获它何时丢失,因此是NoneType

提前感谢您的帮助!

【问题讨论】:

  • 你的导入不应该是from bs4 import BeautifulSoup吗?因为BeautifulSoup4bs4 模块中
  • @salmanwahed 是的,我看到其他网站提到 bs4,但是当我安装(通过 easy_install)时,基本库就是 BeautifulSoup。我在其他领域使用它没有问题,所以我怀疑这是 BeautifulSoup 的另一个(更新?)版本?不知道为什么会有差异...

标签: python beautifulsoup nonetype


【解决方案1】:

看起来只是一个错字。它应该是 soup.findAll 而不是 soup.find_all。我尝试运行它,它适用于更正。所以完整的程序应该是:

import BeautifulSoup
import re

soup = BeautifulSoup.BeautifulSoup(<html page of interest>)
if (soup.findAll("td", attrs= {"class": "FilterElement"}, text= re.compile("HERE IS TEXT I AM LOOKING FOR")) is None):
    print('There was no entry')
else:
    print(soup.find("td", attrs= {"class": "FilterElement"}, text= re.compile("HERE IS THE TEXT I AM LOOKING FOR")))<html page of interest>

【讨论】:

  • 非常感谢!我要到晚上晚些时候才能检查,但我会在那个时候打一个“接受”的复选标记。
  • find_all 在版本 4+ 中是正确的。 findAll 仍然可以工作,但 find_all 更 Pythonic:见 stackoverflow.com/questions/12339323/…
猜你喜欢
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-03
相关资源
最近更新 更多