Python爬虫爬取天气预报信息

目标天气预报网站:http://www.weather.com.cn/weather/101210701.shtml

需要用到的库有requests(用来发送请求和接收url)BeautifulSoup(用来解析html文本)

爬虫的基本思路:
1.首先发送请求并返回requests(最好模拟谷歌浏览器的头部访问(即下面的headers),并且设置一个每次访问的间隔时间,这样就不容易触发网站的反爬机制(说白了就是模拟人类的访问行为))
2.获得requests对象后使用BeautifulSoup来解析requests对象,注意这里要用request.text,就取文本,解析后的soup打印出来其实就是整个html的字符串内容,但是类型并不是string,是bs4类型,它可以直接在python用类似于ccs选择器那样的方式一层一层的寻找我们要的div内容。
3.搜寻soup对象中我们需要的内容,就是一层一层div找到对应的属性,然后拿取我们需要的内容。(看html或者把之前的soup对象打印出来)
20201121152318554

4.打印或保存文件

所有代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}
url= 'http://www.weather.com.cn/weather/101210701.shtml'
res = requests.get(url, headers=headers,timeout=20)
res.encoding = 'utf-8'
#print(res.status_code)
soup = BeautifulSoup(res.text,'html.parser')
tem_list = soup.find_all('p',class_='tem') #存温度
#print(tem_list)
day = soup.find('ul',class_='t clearfix') #存日期
day_list = day.find_all('h1')
#print(day_list)
wealist = soup.find_all('p',class_='wea') #存天气
day_pre = {}

for i in range(7):
try:
temHigh = tem_list[i].span.string #有时候没有最高温度,用第二天的代替
except AttributeError as e:
temHigh = tem_list[i+1].span.string
temLow = tem_list[i].i.string
wea = wealist[i].string
day_pre[day_list[i].string] = '最高温度:'+temHigh +' 最低温度:' + temLow + ' 天气:' + wea
print(day_pre)

结果:

20201121152423295