首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >AttributeError:“NoneType”对象没有属性“查找”BeautifulSoup soup.find错误

AttributeError:“NoneType”对象没有属性“查找”BeautifulSoup soup.find错误
EN

Stack Overflow用户
提问于 2021-11-09 21:58:25
回答 2查看 2.7K关注 0票数 0

我试图从weather.com中提取天气数据,但由于某些原因,它无法工作,这是一个错误:

代码语言:javascript
运行
复制
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    all=soup.find("div",{"class":"locations-title ten-day-page-title"}).find("h1").text
AttributeError: 'NoneType' object has no attribute 'find'

我不知道这里出了什么问题。以下是代码:

代码语言:javascript
运行
复制
import requests
from bs4 import BeautifulSoup
page = requests.get("https://weather.com/en-IE/weather/tenday/l/bf217d537cc1c8074ec195ce07fb74de3c1593caa6033b7c3be4645ccc5b01de")
soup = BeautifulSoup(page.content,"html.parser")

all=soup.find("div",{"class":"locations-title ten-day-page-title"}).find("h1").text
table=soup.find_all("table",{"class":"twc-table"})
l=[]
for items in table:
 for i in range(len(items.find_all("tr"))-1):
  d = {}  
  d["day"]=items.find_all("span",{"class":"date-time"})[i].text
  d["date"]=items.find_all("span",{"class":"day-detail"})[i].text
  d["desc"]=items.find_all("td",{"class":"description"})[i].text 
  d["temp"]=items.find_all("td",{"class":"temp"})[i].text 
  d["precip"]=items.find_all("td",{"class":"precip"})[i].text
  d["wind"]=items.find_all("td",{"class":"wind"})[i].text  
  d["humidity"]=items.find_all("td",{"class":"humidity"})[i].text 
  l.append(d)

我真的不明白这里发生了什么,因为我对python和整个库都很陌生。我希望有人能帮我解决这个问题。

EN

Stack Overflow用户

发布于 2021-11-10 05:00:34

几件事:

正如注释中所指出的,

  1. 是您的第一个soup.find没有返回,因此出错。查看相关的标题,类名有动态的部分。相反,我将使用一个属性=值css选择器(从操作符开始),通过子字符串将类属性作为目标。我还会添加h1类型选择器,从而确保在不链接调用的情况下直接针对h1。

  1. 避免使用已经是关键字或python的变量名称,即all().

因此,重写可能类似于:

代码语言:javascript
运行
复制
import requests
from bs4 import BeautifulSoup

page = requests.get("https://weather.com/en-IE/weather/tenday/l/bf217d537cc1c8074ec195ce07fb74de3c1593caa6033b7c3be4645ccc5b01de")
soup = BeautifulSoup(page.content,"html.parser")
title = soup.select_one('h1[class^=LocationPageTitle]').text
title
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69905610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档