【发布时间】:2021-06-06 06:37:11
【问题描述】:
我为 Stack Overflow 编写了一个网络爬虫,但它不起作用。显然,在我的汤中,有无处可寻的 NoneType 对象。这是网络爬虫代码:
import requests
from bs4 import BeautifulSoup
url = 'https://stackoverflow.com/questions?tab=newest&page='
r = requests.post(url)
soup = BeautifulSoup(r.text, 'lxml').find('div', id='questions').find_all('div')
for summary in soup: # FIXME: Prints each question twice
try:
print(f'Question: {summary.h3.text}')
print(f'Tags: {", ".join(summary.find("div", class_="tags").text[1:].split(" "))}')
except Exception as e:
print(e) # Prints "'NoneType' has no attribute 'text'" which shouldn't be in the soup
我得到的错误(如果您没有阅读评论)是“'NoneType' 没有属性'text'”,这让我很困惑,因为汤中有 NoneType 对象。
我正在使用:
- Windows 10
- Python 3.8
【问题讨论】:
-
您是否尝试使用
.find_all(class_='question-summary')而不是.find_all('div')?当您使用.find_all('div')时,它会针对每个容器中的所有 div。一些 div 不包含您要查找的任何内容,这就是导致该错误的原因。尝试找到一些独特的东西,如class、id等。顺便说一句,你也可以使用.find_all('div',recursive=False)来解决这个问题。
标签: python python-3.x web-scraping beautifulsoup python-requests