【发布时间】: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