已有183人关注
微信机器人-天气爬取bug
发表在Python图书答疑 2023-12-08 《Python项目开发案例集锦》第23章 微信机器人 573页-573页
是否精华
版块置顶:
import requests
from lxml import etree
from random import randint
def get_weather(keyword):
    url = "https://www.tianqi.com?tianqi?search?kryword=" + keyword
    headers = {'User-Agent': 'Mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebkit/537.36(KHTML,like Gecko) Chrome/68.0.3440,106 Safari/537.36'}
    response = requests.get(url,headers=headers)
    tree = etree.HTML(response.text)
    print(tree)
    try:
        city_name = tree.xpath('//dd[@class="name"]/h2/text()')[0]
    except:
        content = '没有该城市天气信息,请确认查询格式'
        return content
    week = tree.xpath('//dd[@class="week"]/text()')[0]
    now = tree.xpath('//p[@ciass="now"]')[0].xpath('string(.)')
    temp = tree.xpath('//dd[@class="weather"]/span')[0].xpath('string(.)')
    shidu = tree.xpath('//dd[@class="shidu"]/b/text()')
    kongqi = tree.xpath('//dd[@class="kongqi"]/h5/text()')[0]
    pm = tree.xpath('//dd[@class="kongqi"]/h6/text()')[0]
    content = "【{0}】{1}天气\n当前温度:{2}\n今日天气:{3}\n{4}\n{5}\n{6}".format(city_name, week.split('\u3000')[0], now, temp, '\n'.join(shidu),kongqi,pm,)
ans = input('城市')
weather = get_weather(ans)
print(weather)

结果:

城市长沙

<Element html at 0x209b4a13640>

没有该城市天气信息,请确认查询格式

程序运行结束。

错哪里了?



分享到:
手机同步功能介绍
友情提示:以下图书配套资源能够实现手机同步功能
明日微信公众号
明日之星 明日之星编程特训营
客服热线(每日9:00-17:00)
400 675 1066
mingrisoft@mingrisoft.com
吉林省明日科技有限公司Copyright ©2007-2022,mingrisoft.com, All Rights Reserved长春市北湖科技开发区盛北大街3333号长春北湖科技园项目一期A10号楼四、五层
吉ICP备10002740号-2吉公网安备22010202000132经营性网站备案信息 营业执照