【问题标题】:Keep getting 'TypeError: 'NoneType' object is not callable' with beautiful soup and python3用漂亮的汤和 python3 不断收到'TypeError:'NoneType'对象不可调用'
【发布时间】:2019-02-02 06:13:07
【问题描述】:

我是一个初学者并且在课程中挣扎,所以这个问题可能真的很简单,但我正在运行这个(当然是混乱的)代码(保存在文件 x.py 下)从一个网站中提取一个链接和一个名称行格式如:

<li style="margin-top: 21px;">
  <a href="http://py4e-data.dr-chuck.net/known_by_Prabhjoit.html">Prabhjoit</a>
</li>

所以我设置了这个: 导入 urllib.request、urllib.parse、urllib.error 从 bs4 导入 BeautifulSoup 导入 ssl # 忽略 SSL 证书错误 ctx = ssl.create_default_context() ctx.check_hostname = 假 ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')
for line in soup:
    if not line.startswith('<li'):
        continue
    stuff = line.split('"')
    link = stuff[3]
    thing = stuff[4].split('<')
    name = thing[0].split('>')
    count = count + 1
    if count == 18:
        break
print(name[1])
print(link)

它不断产生错误:

Traceback (most recent call last):
  File "x.py", line 15, in <module>
    if not line.startswith('<li'):
TypeError: 'NoneType' object is not callable

我已经为此苦苦挣扎了好几个小时,如果有任何建议,我将不胜感激。

【问题讨论】:

  • 我不确定您为什么要在 BeautifulSoup 元素上使用 代码来分割文本。请做read the library documentation,您会发现提供的 API 与您在这里使用的非常不同。
  • 如果要使用startswith,请先转换成字符串。

标签: python beautifulsoup typeerror nonetype


【解决方案1】:

line 不是字符串,它没有startswith() 方法。它是一个BeautifulSoup Tag object,因为 BeautifulSoup 已将 HTML 源文本解析为丰富的对象模型。不要试图将其视为文本!

这个错误是因为如果你访问Tag对象上它不知道的任何属性,它会执行search for a child element with that name(所以这里它执行line.find('startswith')),因为没有元素那个名字,None 被返回。 None.startswith() 然后失败并出现您看到的错误。

如果您想找到第 18 个 &lt;li&gt; 元素,只需向 BeautifulSoup 询问该特定元素:

soup = BeautifulSoup(html, 'html.parser')
li_link_elements = soup.select('li a[href]', limit=18)
if len(li_link_elements) == 18:
    last = li_link_elements[-1]
    print(last.get_text())
    print(last['href'])

这使用CSS selector 仅查找其父元素为&lt;li&gt; 元素且具有href 属性的&lt;a&gt; 链接元素。搜索仅限于 18 个这样的标签,并打印最后一个,但前提是我们实际上在页面中找到了 18 个。

使用Element.get_text() method 检索元素文本,其中将包括来自任何嵌套元素的文本(例如&lt;span&gt;&lt;strong&gt; 或其他额外标记),并且href 属性为accessed using standard indexing notation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 2012-04-28
    • 2021-08-18
    • 2016-10-10
    相关资源
    最近更新 更多