20231120_python练习_天气网爬取城市近七天温度情况

先根据城市名找到对应编码,然后获取近七天天气情况

淄博 101120301 '20日(今天)' '晴' <class 'list'> '7℃' '\\n', '\<3级', '\\n'

淄博 101120301 '21日(明天)' '晴转阴' <class 'list'> '20℃', '8℃' '\\n', '\<3级', '\\n'

淄博 101120301 '22日(后天)' '多云' <class 'list'> '17℃', '3℃' '\\n', '\<3级', '\\n'

淄博 101120301 '23日(周四)' '晴' <class 'list'> '8℃', '-5℃' '\\n', '3-4级转\<3级', '\\n'

淄博 101120301 '24日(周五)' '晴转多云' <class 'list'> '5℃', '-5℃' '\\n', '\<3级', '\\n'

淄博 101120301 '25日(周六)' '阴转多云' <class 'list'> '9℃', '0℃' '\\n', '\<3级', '\\n'

淄博 101120301 '26日(周日)' '晴' <class 'list'> '12℃', '-2℃' '\\n', '\<3级', '\\n'

复制代码
import requests
import json
from lxml import etree

city_dic = {}
text_mw = '淄博'
#将中文转置为字符
text_id = str(text_mw.encode('utf-8')).upper().replace('\\X','%')[2:-1]
print('text_id',text_id)

url = 'http://toy1.weather.com.cn/search?cityname=' + text_id
#设置请求头
header={
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.43",
    "Referer":"http://www.weather.com.cn/", 
    "Cookie":"Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1700397713; f_city=%E6%B5%8E%E5%8D%97%7C101120101%7C; Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b=1700398953"
}
resp = requests.get(url=url,headers=header)
print(resp.status_code)

data = resp.text[1:-1]
json_data = json.loads(data)[0]['ref'][0:9]
#获取城市对应编码
print(json_data)
#淄博 101120301
city_url = 'http://www.weather.com.cn/weather/' + json_data + '.shtml'
print(city_url)
city_resp = requests.get(url=city_url,headers=header)
city_resp.encoding = city_resp.apparent_encoding
html = etree.HTML(city_resp.text)
node_all = html.xpath('//ul[@class="t clearfix"]/li')
#print('节点名称',[i.tag for i in node_all])
for node in node_all:
    day_text = node.xpath('.//h1/text()')
    wea_text = node.xpath('.//p[@class="wea"]/text()')
    tem_text = node.xpath('.//p[@class="tem"]//text()')
    for tem in tem_text:
        if tem in ('/','\n'):tem_text.remove(tem)
    win_text = node.xpath('.//p[@class="win"]//text()')
    for win in win_text:
        if win in ('/','\n'):win_text.remove(win)
    print(text_mw,json_data,day_text,wea_text,type(tem_text),tem_text,win_text)
相关推荐
*neverGiveUp*11 分钟前
Python基础语法
开发语言·python
努力努力再努力wz14 分钟前
【Qt入门系列】一文掌握 Qt 常用显示类控件:QLCDNumber、QProgressBar 与 QCalendarWidget
c语言·开发语言·数据结构·数据库·c++·git·qt
Marst Code16 分钟前
[特殊字符] 五大 Workflow 模式详解
人工智能·python
小白学大数据22 分钟前
爬虫优化:Python 剔除无效超时代理实操
服务器·爬虫·python
右耳朵猫AI27 分钟前
JS/TS周刊2026W21 | Deno2.8RC、Angular22RC、TypeORM1.0
开发语言·javascript·ecmascript
闪电悠米32 分钟前
黑马点评-秒杀优化-02_lua_precheck
开发语言·redis·分布式·缓存·junit·wpf·lua
盈建云系统33 分钟前
外贸网站SEO怎么做?从产品关键词到询盘页面,独立站内容优化流程和费用参考
开发语言·网站搭建
lianyinghhh34 分钟前
FlowGame 从零上手:开源 AI 工作流编排框架与 Vue 3 接入实战
python·低代码·开源·vue·rag·flowgame·ai工作流编排
玫幽倩38 分钟前
2026盘古石取证决赛(APK取证)
数据库·python·电子取证·aes·隐藏·笔记软件·手机取证
Dream_ksw39 分钟前
Python多继承之super()继承问题解决
开发语言·python