Python爬取中国天气网
基于requests库制作的爬虫。
使用方法:打开终端输入 “python3 weather.py 北京(或你所在的城市)"
程序正常运行需要在同文件夹下加入一个“data.csv”文件,内容请参考链接: 城市代码
运行效果:
源码:
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("