微信机器人-天气爬取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>
没有该城市天气信息,请确认查询格式
程序运行结束。
错哪里了?