2017-08-06 35 views
1

我正在通過從https://www.wunderground.com/(搜索隨機郵編)獲取日常高/低溫等基本氣象數據來練習網頁掃描。使用BeautifulSoup進行網頁掃描,獲取空列表

我試過我的代碼的各種變化,但它不斷返回一個空的列表,溫度應該在哪裏。我老實說,只是不知道明確我的錯在哪裏。任何人都可以將我指向正確的方向嗎?

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

內容呈現在運行時。所以你不用'request'獲得它。您最好使用提取JavaScript,JSON等的瀏覽器並更新DOM。 –

回答

5

要分析被動態地由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') 
+1

好的,謝謝!在此之前我甚至不知道動態渲染 – rezale

相關問題