爬取天气信息 发表于 2020-07-15 | 分类于 python | 热度 ℃ | 字数统计 219 字 | 阅读时长 1 分钟 使用requests和BeautifulSoup爬取天气信息。 这是从不倒翁问答系统的祖传代码里翻出来的,利用搜狗搜索获取天气信息,开箱即用。 123456789101112131415161718192021222324252627282930313233343536from bs4 import BeautifulSoupimport requestsheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'}def AskSogouWeather(q): url = 'https://www.sogou.com/web?query=%s' % q resp = requests.get(url, timeout=5, headers=headers) soup = BeautifulSoup(resp.text, 'html.parser') rlst = soup.find('div', 'vr-weather161227') if rlst is None: return None md = rlst.find('div', 'more-day') if md is None: return None items = md.find_all('a') item = None today = items[0] for it in items: xxs = it.get('queryinfo', '').split(';') xxs = [x for x in xxs if x != ''] if '今天' in xxs: today = it for xx in xxs: if xx in q: item = it if item is None: item = today res = item.text.replace('\xa0', ' ').replace("\n"," ").strip().replace(' ', ' ') return resdef WeatherRule(q): if '天气' in q and ('怎' in q or '如何' in q): res = AskSogouWeather(q) return resif __name__ == '__main__': print(WeatherRule('明天天气怎么样')) donate the author Donate WeChat Pay Alipay