python 爬取天气并发送到微信
时间: 2023-12-16 08:01:23 浏览: 29
要用Python实现爬取天气并发送到微信,需要先安装所需的库和模块。常用的库有requests、BeautifulSoup和itchat。以下是具体步骤:
1. 安装所需的库:
```
pip install requests
pip install beautifulsoup4
pip install itchat
```
2. 从网站爬取天气信息:
```
import requests
from bs4 import BeautifulSoup
def get_weather():
url = 'http://www.weather.com'
try:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
weather_data = soup.find('div', class_='weather').find('h1').text
return weather_data
except requests.exceptions.RequestException:
return '无法获取天气信息'
weather = get_weather()
```
3. 使用itchat库登录微信并发送天气信息:
```
import itchat
itchat.auto_login(hotReload=True)
# 获取好友列表
friends = itchat.get_friends(update=True)
# 获取第一个好友的UserName
friend = friends[0]['UserName']
# 发送消息给该好友
itchat.send('今天的天气是:' + weather, toUserName=friend)
```
以上是用Python爬取天气并发送到微信的简单实现。你可以根据实际需求进行进一步的功能扩展和优化。