Skip to main content
 首页 » 编程设计

python之使用 BeautifulSoup 进行网页抓取,得到空列表

2025年05月04日23www_RR

我正在通过获取基本天气数据(例如来自 https://www.wunderground.com/ 的每日高/低温)来练习网络抓取(随机搜索邮政编码)。

我已经尝试了我的代码的各种变体,但它总是在温度应该是的位置返回一个空列表。老实说,我只是不知道自己哪里出错了。谁能指出我正确的方向?

import requests 
from bs4 import BeautifulSoup 
response=requests.get('https://www.wunderground.com/cgi-bin/findweather/getForecast?query=76502') 
response_data = BeautifulSoup(response.content, 'html.parser') 
results=response_data.select("strong.high") 

我还尝试过执行以下操作以及其他各种变体:

results = response_data.find_all('strong', class_ = 'high') 
results = response_data.select('div.small_6 columns > strong.high' ) 

请您参考如下方法:

您要解析的数据是由 JavaScript 动态创建的,requests 无法处理。你应该使用 selenium连同 PhantomJS或任何其他司机。下面是一个使用 selenium 和 Chromedriver 的例子:

from selenium import webdriver 
from bs4 import BeautifulSoup 
 
url='https://www.wunderground.com/cgi-bin/findweather/getForecast?query=76502' 
driver = webdriver.Chrome() 
driver.get(url) 
html = driver.page_source 
 
soup = BeautifulSoup(html, 'html.parser') 

检查元素,可以使用以下方法找到最低、最高和当前温度:

high = soup.find('strong', {'class':'high'}).text 
low = soup.find('strong', {'class':'low'}).text 
now = soup.find('span', {'data-variable':'temperature'}).find('span').text 

>>> low, high, now 
('25', '37', '36.5')