python爬虫全国天气网

python的爬虫练习项目,爬取天气,并且画出查询天气的最近七日的最高温,最低温的折线图

import requests
from bs4 import BeautifulSoup
#目标页面
city = input("请设置地点,省份+市+地区,如广东,珠海\n")
#注意此切片的逗号用的是英文下的
city = city.split(',')

url="https://tianqi.2345.com/china.htm"
#浏览器右键检查,network然后找doc,刷新页面,在文档里找"User-Agent",User-Agent其实就是你的浏览器信息
headers = {
 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",

}
def first(url):
    #函数外要使用x定义成global
    global x
    try:
        response = requests.get(url, headers=headers)
        #防止中文乱码
        response.encoding = 'utf-8'
        #它能够判断返回的Response类型状态是不是200。如果是200,他将表示返回的内容是正确的,如果不是200,他就会产生一个HttpError的异常。
        if response.status_code == 200:

            x = BeautifulSoup(response.text, 'lxml')
            #print(response.text)

    except:
        print("爬取失败")
#运行函数,总网页上找到广东省
first("https://tianqi.2345.com/china.htm")
weatherprovince = x.find_all('a', title=city[0]+"天气")
print(weatherprovince)
#[<a href="/guangdong_dz/15.htm" onclick="allCount('全国天气_点击_全国天气_广东')" target="_blank" title="广东天气">广东</a>]
#取出/guangdong_dz/15.htm
print(weatherprovince[0].get("href"))
#组成进入省份的url
url1="https://tianqi.2345.com"+weatherprovince[0].get("href")
first(url1)
#由省份的url里拿到城市的url
weathercity = x.find_all('a', title=city[1]+"天气")
print(weathercity)

#/zhongshan1d/59485.htm
print(weathercity[0].get("href"))
url2="https://tianqi.2345.com"+weathercity[0].get("href")
#进入城市的url,但是城市的页面里未找到温度,需要进去七日天气实际链接为https://tianqi.2345.com/today-59485.htm因此改用下面的url2
city = weathercity[0].get("href").split('/')
print(city)
#city中的内容['', 'zhongshan1d', '59485.htm']
url2="https://tianqi.2345.com/"+"today-"+city[2]
print(url2)
first(url2)
bytes_obj = x.prettify().encode()
with open('weather1.html', 'wb') as f:
    f.write(bytes_obj)
print('ok')

from lxml import etree
parser = etree.HTMLParser(encoding='utf-8')
html = etree.parse('weather1.html', parser=parser)
str=html.xpath('//body/div/div/div/div/div/ul/li/a/span[@class="tem-show"]/text()')
#取出一周温度['14~23°', '15~24°', '16~25°', '16~26°', '17~27°', '17~28°', '16~26°', '16~25°']
print(str)
list=[]
for i in str:
    i=i.strip()
    print(i)
    list.append(i)
print(list)
#分别取出最低和最高温
listlow=[]
listhigh=[]
for i in list:
    a=i.split('~')
    print(a)
    listlow.append(int(a[0]))
    listhigh.append(a[1])
print(listlow)
print(listhigh)
#最高温有温度符号,如果去掉['23°', '24°', '25°', '26°', '27°', '28°', '26°', '25°']
listnew=[]
for i in listhigh:
    a=i.split('°')
    print(a)
    listnew.append(int(a[0]))
print(listnew)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
font = fm.FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf")
plt.xlabel(city[1],fontproperties=font)
plt.ylabel('温度',fontproperties=font)
#x轴的坐标设计
plt.xticks(np.arange(8),('1','2','3','4','5','6','7','8'),fontproperties=font)
#设计图的整体宽度和n,n越大柱越小因为width(单柱的宽度)越小,total越大柱子越宽
total_width,n=0.8,5
width=total_width/n
#柱子起始位置
x=np.arange(8)
#以下第一个参数为x轴上的偏移位
plt.plot(x,listlow, color='green',alpha=0.8,marker='o',linestyle='--',linewidth=1,label='低温')
plt.plot(x,listnew, color='red',alpha=0.8,marker='o',linestyle='--',linewidth=1,label='高温')
plt.legend(prop=font)

plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值