您当前的位置: 首页 >  Python

嗨学编程

暂无认证

  • 0浏览

    0关注

    1405博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Python爬取中国天气网

嗨学编程 发布时间:2019-04-15 15:41:53 ,浏览量:0

基于requests库制作的爬虫。

使用方法:打开终端输入 “python3 weather.py 北京(或你所在的城市)"

程序正常运行需要在同文件夹下加入一个“data.csv”文件,内容请参考链接: 城市代码

运行效果:

源码:

'''
想要学习Python?Python学习交流群:973783996满足你的需求,资料都已经上传群文件,可以自行下载!
'''
import sys
import re
import requests
import webbrowser
from PIL import Image
from requests.exceptions import RequestException
import csv
data={}
with open("data.csv",'r') as f:
    rawinfos=list(csv.reader(f))
    for i in rawinfos:
        data[i[0]]=i[1]
def get_one_page(url,headers):
    try:
        response=requests.get(url,headers=headers)
        if response.status_code==200:
            response.encoding='utf-8'
            return response.text
        return None
    except RequestException:
        return None
headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0.2 Safari/604.4.7'}
try:
    address=data[sys.argv[1]]
except:
    sys.exit("\033[31m无该城市!\033[0m")
html=get_one_page('http://www.weather.com.cn/weather1d/'+address+'.shtml',headers)
if not html:
    print("城市代码有误!")
    exit(1)
ADDRESS=re.findall('(.*?)',html)
aim=re.findall('            
关注
打赏
1663681728
查看更多评论
0.0488s