python爬取中国天气网的天气

越来越多的天气开始进行收费了,今天想到用python爬取其他网站上的天气,岂不美哉

import requests as rq
import json
import re


def print_hi(name):
    # 城市Id,城市ID对照表放下面了,若是获取可根据IP地址获取地区,然后再对照下面的对照表进行动态获取
    cityId = '101110101'
    url = 'http://d1.weather.com.cn/weather_index/' + cityId + '.html'
    res = rq.get(url)
    resText = res.text.encode(res.encoding).decode(res.apparent_encoding)
    cityDZ = re.findall(r'var cityDZ =.*?;', resText)[0]
    print(cityDZ[12:-1])
    dataSK = re.findall(r'var dataSK =.*?;', resText)[0]
    print(dataSK[12:-1])
    dataZS = re.findall(r'var dataZS =.*?;', resText)[0]
    print(dataZS[12:-1])
    fc = re.findall(r'var fc =(.*)', resText)[0]
    print(fc)
    cityDZJson = json.loads(cityDZ[12:-1])
    print('城市:' + cityDZJson['weatherinfo']['city'])
    print('天气:' + cityDZJson['weatherinfo']['weather'])
    print('最高温度:' + cityDZJson['weatherinfo']['temp'])
    print('最低温低:' + cityDZJson['weatherinfo']['tempn'])
    print('风向:' + cityDZJson['weatherinfo']['wd'])
    print('风向强度:' + cityDZJson['weatherinfo']['ws'])
	# 其他的字段请自行获取

if __name__ == '__main__':
    print_hi('PyCharm')

说我字数太多,不给发布,没办法了,放到git上https://gitee.com/lk666/happy-birthday/blob/master/other/city.js

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
好的,您想了解如何用 Python 爬取历史天气数据,是吗? 首先,需要确定您想要爬取哪个地区的历史天气数据。一般来说,可以通过查询该地区的气象局或气象站获取历史天气数据。 接着,可以使用 Python 中的 requests 库来发送 HTTP 请求,获取页源代码。然后,可以使用 BeautifulSoup 库来解析页源代码,提取出所需的天气数据。 以下是一个简单的示例代码,用于爬取中国天气上北京市 2019 年 1 月份的历史天气数据: ``` python import requests from bs4 import BeautifulSoup url = 'http://www.weather.com.cn/weather/101010100.shtml#dt' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} r = requests.get(url, headers=headers) r.encoding = 'utf-8' soup = BeautifulSoup(r.text, 'html.parser') weather_list = soup.select('.t li') for weather in weather_list: date = weather.select('.time')[0].text weather_detail = weather.select('.temp')[0].text.strip() print(date, weather_detail) ``` 以上代码中,我们首先通过 requests 库发送了一个 GET 请求,获取了北京市天气页源代码。然后,使用 BeautifulSoup 库解析页源代码,提取出了 2019 年 1 月份的天气数据,并打印输出了日期和天气详情。 需要注意的是,不同的页结构不同,需要根据具体情况修改代码。同时,需要注意站的 robots.txt 文件,不要过度访问站,以免被封 IP 或其他限制。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值