簡體   English   中英

Web 用Python BS刮

[英]Web Scraping with Python BS

試圖從 Weather Underground 中抓取一些天氣數據。 在獲取日期/日期、高/低溫度和預報(即“部分多雲”)之前,我沒有遇到任何困難獲取感興趣的數據。 每個都在一個沒有 class 的 div 中。 每個的父級是一個帶有 class="obs-date" 的 div(見下圖)

[WxUn HTML 圖像][1]

下面嘗試的代碼帶有注釋掉的其他選項。 每個返回一個空列表。

def get_wx(city, state):
    city=city.lower()
    state=state.lower()
    
    # get current conditions; 'weather' in url
    current_dict = get_current(city, state)

    # get forecast; 'forecast' in url
    f_url = f'https://www.wunderground.com/forecast/us/{state}/{city}'
    f_response = req.get(f_url)
    f_soup = BeautifulSoup(f_response.text, 'html.parser')
    cast_dates = f_soup.find_all('div', class_="obs-date")
    # cast_dates = f_soup.find_all('div', attrs={"class":"obs-date"})
    # cast_dates = f_soup.select('div.obs-date')
    print(cast_dates)
    
get_wx("Portland", "ME")

對我所缺少的任何幫助表示贊賞。

據我所知,您嘗試解析的整個塊是由 javascript 驅動的,這就是為什么您使用beautifulsoup得到空結果的原因

可以使用bs4以及以下所有內容完全解析附加條件部分。 最后的表格可以使用pandas解析。

要抓取 javascript 內容,您可以使用requests-htmlselenium庫。

from requests_html import HTMLSession
import json

session = HTMLSession()
url = "https://www.wunderground.com/weather/us/me/portland"
response = session.get(url)
response.html.render(sleep=1)

data = []

current_date = response.html.find('.timestamp strong', first = True).text
weather_conditions = response.html.find('.condition-icon p', first = True).text
gusts = response.html.find('.medium-uncentered span', first = True).text
current_temp = response.html.find('.current-temp .is-degree-visible', first = True).text

data.append({
    "Last update": current_date,
    "Current weather": weather_conditions,
    "Temperature": current_temp,
    "Gusts": gusts,
})

print(json.dumps(data, indent = 2, ensure_ascii = False))

Output:

[
  {
    "Last update": "1:27 PM EDT on April 14, 2021",
    "Current weather": "Fair",
    "Temperature": "49 F",
    "Gusts": "13 mph"
  }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM