类型错误: + 不支持的操作数类型:"NoneType"和"str" - 使用 BeautifulSoup



我是Python的新手,这是我的代码:

#!venv/bin/python
import sys
import requests
import bs4
if len(sys.argv) == 3:
# If arguments are satisfied store them in readable variables
url = 'http://%s' % sys.argv[1]
file_name = sys.argv[2]
print('Grabbing the page...')
# Get url from command line
response = requests.get(url)
response.raise_for_status()
# Retrieve all links on the page
soup = bs4.BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a')
file = open(file_name, 'wb')
print('Collecting the links...')
for link in links:
    href=link.get("href") + "n"
    file.write(href.encode())
file.close()
print('Saved to %s' % file_name)
else:
print('Usage: ./collect_links.py www.example.com file.txt')

我面临以下错误:

Traceback (most recent call last):
  File "collect_links.py", line 23, in <module>
    href=link.get("href") + ("n")
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

我已经尝试了几件事,但我需要附加一行,有什么想法吗?我将不胜感激任何帮助!

谢谢

错误消息意味着 link.get("href"( 的值为 None。因此,Python 无法对 None 和字符串执行操作数"sum"。我建议您尝试通过打印变量"links"进行调试,以检查您获得的值以及为什么当您尝试 .get("href"( 时会得到 None。

最新更新