写一段爬取天气的python代码
时间: 2023-05-28 17:02:24 浏览: 113
可以使用第三方库 requests 和 BeautifulSoup 来爬取天气信息。代码如下:
```
import requests
from bs4 import BeautifulSoup
def get_weather(city_name):
# 请求 URL
url = f'https://www.google.com/search?q={city_name}天气'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 发送请求,获取网页数据
response = requests.get(url, headers=headers)
response.raise_for_status()
# 解析网页数据
soup = BeautifulSoup(response.text, 'lxml')
weather_info = soup.select_one('#wob_tm').text
weather = soup.select_one('#wob_dc').text
return weather_info, weather
city_name = '北京'
weather_info, weather = get_weather(city_name)
print(f'{city_name}的天气:{weather_info} {weather}')
```
这段代码实现了通过爬取 Google 搜索的天气结果来获取天气信息。
阅读全文