前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >爬取天气信息

爬取天气信息

作者头像
luxuantao
发布2021-02-24 11:30:22
6000
发布2021-02-24 11:30:22
举报
文章被收录于专栏:Fdu弟中弟Fdu弟中弟

使用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('明天天气怎么样'))
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-07-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档