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)

然后我们运行:
得到天气情况为雷阵雨
在这里插入图片描述网址天气情况也为雷阵雨


问题:第二个输出为温度数值,不知为何输出为None;
于是我将第七行后面的.int去除,得到运行结果:
在这里插入图片描述成功爬取,可是没有将温度数据提出,知道的大佬希望可以指点一下

猜你喜欢

转载自blog.csdn.net/qq_44419932/article/details/106251001