使用requests和BeautifulSoup时出现AttributeError: 'NoneType'无'text'属性
问题分析与解决方案
你遇到的AttributeError: 'NoneType' object has no attribute 'text',本质是soup.find()未找到目标元素,返回了None,后续直接调用.text触发报错。核心问题有三个:
1. URL构造错误
placeWeather = "Weather in", place 创建的是元组而非字符串,拼接到URL后会变成类似 https://www.google.com/search?q=('Weather in', 'Delhi'),这不是有效的搜索请求,Google返回的不是正常天气结果页,自然找不到目标元素。
2. 缺少请求头被反爬拦截
直接用requests.get()发送请求,Google会识别出爬虫身份,返回验证页面或简化版内容,导致无法定位气温元素。
3. 未处理元素未找到的边界情况
即使修复前两个问题,也可能因页面结构变动导致元素找不到,直接调用.text必然报错,需要先判断元素是否存在。
修正后的代码
import requests from bs4 import BeautifulSoup class Temperature: @staticmethod def temperature(place): # 构造正确的搜索关键词字符串 search_query = f"Weather in {place}" url = f"https://www.google.com/search?q={search_query}" # 添加请求头,模拟浏览器访问 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } try: r = requests.get(url, headers=headers) r.raise_for_status() # 检查请求是否成功 soup = BeautifulSoup(r.text, "html.parser") # 定位气温元素(Google页面结构可能随时变化,需按需调整) temp_element = soup.find("div", class_="wob_t q8U8x") if temp_element: temp = temp_element.text print(f"{search_query} is {temp}") return temp else: print("无法找到气温信息,可能页面结构已更新") return None except Exception as e: print(f"请求出错: {str(e)}") return None # 调用示例 t = Temperature.temperature("Delhi") print(t)
额外提示
- Google页面结构会频繁更新,如果再次出现找不到元素的情况,需打开浏览器开发者工具,重新定位气温元素的标签和属性。
- 请求头中的
User-Agent可根据自己的浏览器版本调整,避免被拦截。
内容的提问来源于stack exchange,提问作者vivaanlord0Fall
相关产品推荐
相关产品推荐

