爬取天气信息

2021-02-24 11:30:22 浏览数 (3)

使用requests和BeautifulSoup爬取天气信息。

这是从不倒翁问答系统的祖传代码里翻出来的,利用搜狗搜索获取天气信息,开箱即用。

代码语言:javascript复制
from bs4 import BeautifulSoup
import requests


headers = {'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 res

def WeatherRule(q):
	if '天气' in q and ('怎' in q or '如何' in q): 
		res = AskSogouWeather(q)
		return res


if __name__ == '__main__':
	print(WeatherRule('明天天气怎么样'))

0 人点赞