我正在写我的第一个“真正的”项目,一个网络爬虫,我不知道如何修复这个错误。这是我的代码
import requests
from bs4 import BeautifulSoup
def main_spider(max_pages):
page = 1
for page in range(1, max_pages+1):
url = "https://en.wikipedia.org/wiki/Star_Wars" + str(page)
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
for link in soup.findAll("a"):
href = "https://en.wikipedia.org/wiki/Star_Wars" + link.get("href")
print(href)
page += 1
main_spider(1)
这是错误
href = "https://en.wikipedia.org/wiki/Star_Wars" + link.get("href")
TypeError: must be str, not NoneType
原文由 Dylan Boyd 发布,翻译遵循 CC BY-SA 4.0 许可协议
正如@Shiping 所指出的,您的代码没有正确缩进……我在下面更正了它。另外…
link.get('href')
在其中一种情况下不返回字符串。为了评估正在发生的事情,我添加了几行代码……在你现有的几行之间并删除了有问题的行(暂时)。
我添加的结果是这样的(为简洁起见被截断): 注意:第一个锚点没有 href 属性,因此
link.get('href')
无法返回值,因此返回None
为防止错误,可能的解决方案是向代码中添加条件或 try/except 表达式。我将演示一个条件表达式。