【问题标题】:Webscraping with BeautifulSoup, getting empty list使用 BeautifulSoup 进行网页抓取,得到空列表
【发布时间】:2017-08-06 23:34:35
【问题描述】:

我正在通过从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' )

【问题讨论】:

  • 内容在运行时呈现。所以你不能通过requests 获得它。您最好使用能够获取 JavaScript、JSON 等并更新 DOM 的浏览器。

标签: python web-scraping beautifulsoup


【解决方案1】:

您要解析的这些数据是由 JavaScript 动态创建的,requests 无法处理。您应该将seleniumPhantomJS 或任何其他驱动程序一起使用。下面是使用seleniumChromedriver 的示例:

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')

【讨论】:

  • 好的,谢谢!在此之前我什至不知道动态渲染
猜你喜欢
  • 2021-11-15
  • 2018-08-02
  • 1970-01-01
  • 2020-10-04
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多