python - 如何使用 BeautifulSoup 访问 svg 中的元素?
问题描述
我正在从谷歌搜索结果中抓取天气数据。最后,我想从svg graphs
我遇到所有问题的地方抓取数据。
我的代码:
from bs4 import BeautifulSoup as bs
import requests
def get_weather_data(region):
# const values
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36"
LANGUAGE = "en-US,en;q=0.5" # US english
URL = f"https://www.google.com/search?lr=lang_en&q=weather+in+{region.strip().lower().replace(' ', '+')}"
# Send request and store response
s = requests.Session()
s.headers['User-Agent'] = USER_AGENT
s.headers['Accept-Language'] = LANGUAGE
s.headers['Content-Language'] = LANGUAGE
html = s.get(URL)
soup = bs(html.text, "html.parser")
hourly = soup.find("svg", attrs={'id':'wob_gsvg'})
hourly2 = soup.find("svg", attrs={'id':'wob_gsvg'}).children
print(hourly, hourly2)
get_weather_data("London")
输出:
<svg class="wob_gsvg" data-ved="2ahUKEwiToY6r0eLzAhWOpZUCHdMQC0kQnaQEegQIGRAG" id="wob_gsvg" style="height:80px"></svg> <list_iterator object at 0x00000275054D9E20>
但在 chrome 浏览器控制台中,我可以看到:
主要目标
- 做网络抓取 - 来自谷歌搜索结果的天气数据。
- 刮每小时预报可用
解决方案
在html.text
你没有这个数据。
检查它尝试:
with open("data.html", "w") as f:
f.write(html.text)
然后在浏览器上打开此文件。
要解决此问题,请尝试使用selenium
库。
https://selenium-python.readthedocs.io
推荐阅读
- python - Python:如何在熊猫数据框上应用有条件的函数?
- clojure - 如何在 clojurescirpt 的宏中引用函数?
- latex - 更改乳胶中的字体
- javascript - 对使用 JSON 的编码错误以及 JS 和 PHP 之间的差异感到疯狂
- javascript - 有条件地在模块上运行 lerna 命令
- performance - JMETER_HOME 环境变量未正确定义,但构建成功,脚本在 Jmeter GUI 和 cmd 提示符下工作正常
- c - 为什么在第一次输入后连续的 fgets 和 sscanf 不工作
- web-services - 单击 Power BI 中的链接时打开外部程序的 Web 服务
- php - 无法从 php 执行 shell 脚本。返回代码 126
- unit-testing - 如何模拟使用 AWS 资源的打字稿服务和功能?