python爬取地區天氣情況

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)

然後我們運行:
得到天氣情況爲雷陣雨
在這裏插入圖片描述網址天氣情況也爲雷陣雨

![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20200521102705879.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0NDE5OTMy,size_16,color_FFFFFF,t_70)

問題:第二個輸出爲溫度數值,不知爲何輸出爲None;
於是我將第七行後面的.int去除,得到運行結果:
在這裏插入圖片描述成功爬取,可是沒有將溫度數據提出,知道的大佬希望可以指點一下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章