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

使用bs4爬取天气网站:如何选中第二个含%的section并获取42%湿度值

爬取天气网站湿度值的解决方案

核心问题原因

select_one方法只会返回第一个匹配CSS选择器的元素,所以你之前的代码始终拿到的是第一个含%的section,而目标湿度在第二个里。

可行解决方法


方法1:批量获取后指定索引

先获取所有符合条件的section,再通过索引选中第二个(索引从0开始):

# 获取所有包含%的section标签
matched_sections = soup.select('section:-soup-contains("%")')
# 选中第二个section
target_section = matched_sections[1]
# 提取湿度值(根据实际DOM结构调整,示例为直接提取含%的文本)
humd = target_section.get_text(strip=True).split('%')[0] + '%'

方法2:用更精准的选择器定位第二个section

如果第二个section有专属的父容器或类属性,直接用组合选择器定位,比如假设它在class="today-details"的容器内:

humd = soup.select_one('div.today-details section:-soup-contains("%")').text.strip()

方法3:直接定位湿度元素(最可靠)

跳过section层级,通过“Humidity”标签直接关联数值元素,避免section结构变化的影响:

# 找到显示"Humidity"的标签
humidity_label = soup.find(string="Humidity")
# 获取相邻的数值元素文本
humd = humidity_label.find_next('span').text

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:48:03