python爬取地區天氣情況
之前找到一個簡單的爬取地區天氣情況的爬蟲代碼,現在來記錄分享一下
話不多說直接上代碼
from urllib.request import urlopen
from bs4 import BeautifulSoup
resp = urlopen('http://www.weather.com.cn/weather1d/101250301.shtml')
soup = BeautifulSoup(resp, 'html.parser')
tagToday = soup.find('p', class_="tem").int #第一個包含class="tem"的p標籤即爲存放今天天氣數據的標籤
weather = soup.find('p', class_="wea").string #獲取天氣
print(weather)
print(tagToday)
可以看到第4行有個網址,大家可以進入到這個網址,這是中國天氣的網站
大家可以查找自己的地區
然後得到自己地區天氣的網址:
例如北京是:http://www.weather.com.cn/weather1d/101010100.shtml#input
我們還得去掉後面的#input
就得到http://www.weather.com.cn/weather1d/101010100.shtml
將這個網址填入到代碼第4行的網址處:
from urllib.request import urlopen
from bs4 import BeautifulSoup
resp = urlopen('http://www.weather.com.cn/weather1d/101010100.shtml#')
soup = BeautifulSoup(resp, 'html.parser')
tagToday = soup.find('p', class_="tem").int #第一個包含class="tem"的p標籤即爲存放今天天氣數據的標籤
weather = soup.find('p', class_="wea").string #獲取天氣
print(weather)
print(tagToday)
然後我們運行:
得到天氣情況爲雷陣雨
網址天氣情況也爲雷陣雨
問題:第二個輸出爲溫度數值,不知爲何輸出爲None;
於是我將第七行後面的.int去除,得到運行結果:
成功爬取,可是沒有將溫度數據提出,知道的大佬希望可以指點一下