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

如何用BeautifulSoup获取Naver天气图标元素的style属性URL?

获取天气图标style属性中的URL

环境说明

  • 使用模块:BeautifulSoup、requests
  • 爬取目标:Naver天气搜索页面

问题场景

你已经通过以下代码定位到了天气图标元素:

weather_icon = soup.find('div', {'class':'weather_info'}).find('i', {'class':'wt_icon ico_wt6'})

输出的元素结构为:

<i class="wt_icon ico_wt6"><span class="blind">구름많음</span></i>

需要提取该元素style属性中箭头标记的图标URL。

解决方法

1. 获取style属性内容

BeautifulSoup中可以通过get()方法直接获取元素的属性值:

style_attr = weather_icon.get('style')

如果属性存在,style_attr会返回类似background-image:url('https://example.com/icon.png')这样的字符串。

2. 提取URL

通过正则表达式从style字符串中提取URL:

import re

# 兼容单引号和双引号的正则表达式
match = re.search(r"url\(['\"](.*?)['\"]\)", style_attr)
if match:
    icon_url = match.group(1)
    print(icon_url)

注意事项

如果执行后发现style_attr为None,说明当前静态HTML中该元素没有style属性,大概率是页面内容通过JavaScript动态加载的。这种情况下requests无法获取动态渲染后的内容,需要改用selenium等工具模拟浏览器加载页面后再进行解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:52:34