Keep getting 'TypeError: 'NoneType' object is not callable' with beautiful soup and python3

Keep getting 'TypeError: 'NoneType' object is not callable' with beautiful soup and python3

我是初学者,在课程中苦苦挣扎,所以这个问题可能真的很简单,但我运行这个(公认的混乱)代码(保存在文件 x.py 下)提取一个link 和来自网站的名称,其行格式如下:

<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

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

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

错误是因为如果你访问它不知道的Tag对象的任何属性,它会执行search for a child element with that name(所以这里它执行line.find('startswith')) ,并且由于不存在具有该名称的元素,因此返回 NoneNone.startswith() 然后失败并显示您看到的错误。

如果您想找到第 18 个 <li> 元素,只需 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 仅查找其父元素为 <li> 且具有 href 属性的 <a> link 元素。搜索仅限于 18 个这样的标签,并打印最后一个,但前提是我们在页面中实际找到 18 个。

使用 Element.get_text() method, which will include text from any nested elements (such as <span> or <strong> or other extra markup), and the href attribute is accessed using standard indexing notation 检索元素文本。