寻找大连网站建设,立方集团 网站,做网站在阿里云买什么,国内专门做酒的网站有哪些Python爬虫入门实战--------一周天气预报爬取【转载】【没有分析
Python爬虫入门实战--------一周天气预报爬取【转载】【没有分析】
来源#xff1a;https://blog.csdn.net/qq_40705355/article/details/83856960七天天气来源#xff1a;http://www.weather.com.cn/weather/…Python爬虫入门实战--------一周天气预报爬取【转载】【没有分析
Python爬虫入门实战--------一周天气预报爬取【转载】【没有分析】
来源https://blog.csdn.net/qq_40705355/article/details/83856960七天天气来源http://www.weather.com.cn/weather/101120101.shtml
源程序
import csv
import urllib.request
from bs4 import BeautifulSoup模拟浏览器得到数据
#更新为济南的天气网址
url http://www.weather.com.cn/weather/101120101.shtmlheader (User-Agent,Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36) # 设置头部信息
opener urllib.request.build_opener() # 修改头部信息
opener.addheaders [header] #修改头部信息
request urllib.request.Request(url) # 制作请求
response urllib.request.urlopen(request) # 得到请求的应答包
html response.read() #将应答包里面的内容读取出来
html html.decode(utf-8) # 使用utf-8进行编码不重新编码就会成乱码模拟浏览器得到数据
final [] #初始化一个空的list我们为将最终的的数据保存到list
bs BeautifulSoup(html,html.parser) # 创建BeautifulSoup对象
body bs.body # 获取body部分
data body.find(div,{id:7d}) # 找到id为7d的div
ul data.find(ul) # 获取ul部分
li ul.find_all(li) # 获取所有的li
# print (li)
i 0
for day in li: # 对每个li标签中的内容进行遍历
if i 7:
temp []
date day.find(h1).string # 找到日期
# print (date)
temp.append(date) # 添加到temp中
# print (temp)
inf day.find_all(p) # 找到li中的所有p标签
# print(inf)
# print (inf[0])
temp.append(inf[0].string) # 第一个p标签中的内容天气状况加到temp中
if inf[1].find(span) is None:
temperature_highest None # 天气预报可能没有当天的最高气温到了傍晚就是这样需要加个判断语句,来输出最低气温
else:
temperature_highest inf[1].find(span).string # 找到最高温度
temperature_highest temperature_highest.replace(℃, ) # 到了晚上网站会变最高温度后面也有个℃
temperature_lowest inf[1].find(i).string #找到最低温度
temperature_lowest temperature_lowest.replace(℃, ) # # 最低温度后面有个℃去掉这个符号
temp.append(temperature_highest)
temp.append(temperature_lowest)
final.append(temp)
i i 1
# print(final)
with open(weather.csv, a, errorsignore, newline) as f:
f_csv csv.writer(f)
f_csv.writerows(final)
效果图自己分析固定开头
import csv
import urllib.request
from bs4 import BeautifulSoup模拟浏览器得到数据
#更新为济南的天气网址
url http://www.weather.com.cn/weather/101120101.shtml
header (User-Agent,Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36) # 设置头部信息
opener urllib.request.build_opener() # 修改头部信息
opener.addheaders [header] #修改头部信息
request urllib.request.Request(url) # 制作请求
response urllib.request.urlopen(request) # 得到请求的应答包
html response.read() #将应答包里面的内容读取出来
html html.decode(utf-8) # 使用utf-8进行编码不重新编码就会成乱码
自己分析分析
选取元素 特别好用。Python爬虫入门实战--------一周天气预报爬取【转载】【没有分析相关教程