python運用beautifulsoup選擇正確selector獲取天氣預報
阿新 • • 發佈:2019-02-09
以下程式碼實現深圳未來7天天氣預報資訊,程式碼如下,注意在copy selector時不一定正確,要自己檢查並構造
程式碼如下,基於python3.6.4版本
#coding=utf-8 from bs4 import BeautifulSoup import requests import lxml ur1 = 'http://www.weather.com.cn/weather/101280101.shtml' #獲取網頁資料 web_data = requests.get(ur1) # 設為utf-8編碼,預防亂碼 web_data.encoding = 'utf-8' #print(web_data.text) soup = BeautifulSoup(web_data.text, 'html.parser') day = soup.select('ul.t.clearfix > li > h1') weather = soup.select('ul.t.clearfix > li > p.wea') max_tem = soup.select('ul.t.clearfix > li > p.tem > span') min_tem = soup.select('ul.t.clearfix > li > p.tem > i') wind = soup.select('ul.t.clearfix > li > p.win > i') #print(day, weather, max_tem, min_tem, wind) for day, weather, max_tem, min_tem, wind in zip(day, weather, max_tem, min_tem, wind): day_text = day.get_text() weather_text = weather.get_text() max_tem_text = max_tem.get_text() min_tem_text = min_tem.get_text() wind_text = wind.get_text() information = { 'day': day_text, "weather": weather_text, 'max_tem': max_tem_text, 'min_tem': min_tem_text, 'wind': wind_text } print(information)
結果如下