You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Beautiful Soup提取标签title属性失败,求解决方法

问题原因与解决方案

问题根源

你提取不到title属性的核心原因是:这个属性是页面加载后通过JavaScript动态添加的。requests库只能获取服务器返回的原始静态HTML,不会执行页面中的JavaScript代码,所以你拿到的span标签里没有title属性——而你在浏览器中看到的title,是浏览器执行JS后动态生成的。

解决方案

方案1:使用支持JS渲染的工具(以Selenium为例)

通过Selenium模拟浏览器行为,让页面完整执行JS后再获取源码:

from selenium import webdriver
from bs4 import BeautifulSoup
import time

# 初始化Chrome浏览器驱动(需提前下载对应版本的chromedriver)
driver = webdriver.Chrome()
driver.get('https://worldweather.wmo.int/en/city.html?cityId=206')

# 等待JS完成渲染(可根据网络情况调整等待时间)
time.sleep(3)

# 获取渲染后的页面源码
page_source = driver.page_source
driver.quit()

# 解析页面
soup = BeautifulSoup(page_source, 'html.parser')
today_weather = soup.select('#currwx_icon')
for info in today_weather:
    # 用get方法避免属性不存在时抛出KeyError
    print(info.get('title'))

方案2:直接提取静态显示的天气文本

观察页面会发现,天气状态(比如Cloudy)通常会直接显示在页面的某个静态元素中,无需依赖动态属性。例如可以查找页面中的天气描述元素:

import requests
from bs4 import BeautifulSoup

data = requests.get('https://worldweather.wmo.int/en/city.html?cityId=206')
soup = BeautifulSoup(data.text, 'html.parser')

# 提取直接显示的天气文本(示例选择器,需根据实际页面结构调整)
weather_text = soup.select_one('.weather_desc').text.strip()
print(weather_text)

注意事项

  • 使用Selenium时,需确保浏览器驱动版本与你的浏览器版本一致,否则会出现兼容性问题。
  • 提取属性时,优先使用element.get('属性名')而非element['属性名'],前者在属性不存在时返回None,不会抛出KeyError。

内容的提问来源于stack exchange,提问作者gtj520

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:55:23