抓取此网站时遇到问题

时间:2021-07-18 09:20:43

标签: python web-scraping

我想在工作中抓取一个网站,但遇到错误代码问题。这是我的代码。

from bs4 import BeautifulSoup

html = "https://reddit.com" #just an example
soup = BeautifulSoup(requests.get(html).text, 'html.parser')
rootDiv=soup.find('div',attrs={'id':'root'})
if(rootDiv):
   targetdivs=rootDiv.find('div',attrs={'class':'box-bottom'})
   for targetDiv in targetdivs:
       span=targetdivs.find('span',attrs={'class':'box-bottom-offline'})
       if(span):
           print(span.text)


这是我试图刮掉的红色圆圈的片段。

运行代码后出现错误:

TypeError: 'NoneType' 对象不可迭代

任何建议将不胜感激

enter image description here

1 个答案:

答案 0 :(得分:0)

如果您仔细查看 html,'class':'box-bottom' 只出现一次,这也是错误显示 "object不可迭代”,这基本上意味着targetDiv 不是一个可以循环的数组

试试吧

print(targetdivs) 

之后

targetdivs=rootDiv.find('div',attrs={'class':'box-bottom'})

然后你会得到你的答案,希望这会有所帮助