帮我用python写一个爬取城市天气信息的代码
时间: 2024-05-03 10:20:59 浏览: 10
好的,以下是示例代码:
```python
# 导入库
import requests
from bs4 import BeautifulSoup
# 要查询的城市
city = '北京'
# 构建url
url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city
# 发送请求,获取响应
response = requests.get(url)
# 解析html
soup = BeautifulSoup(response.content, 'html.parser')
# 获取天气信息
data = soup.find('div', {'class': 'weather-info'})
# 输出天气信息
print(data.text)
```
这段代码可以爬取指定城市的天气信息并输出。您可以根据自己的需求修改代码来获取更详细的天气信息。
相关问题
写一个爬取百度天气的代码
以下是使用 Python3 编写的爬取百度天气的代码:
```
import requests
from bs4 import BeautifulSoup
city = input("请输入您要查询的城市:")
url = f"https://www.baidu.com/s?ie=UTF-8&wd={city}天气"
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.36 Edge/16.16299"
}
# 发送请求
response = requests.get(url, headers=headers)
# 解析 HTML
soup = BeautifulSoup(response.content, "html.parser")
# 查找天气信息
weather_div = soup.find("div", class_="op_weather4_twoicon")
# 打印天气信息
print(weather_div.text)
```
在运行代码之前,需要先安装 requests 和 bs4 两个库,可以使用以下命令进行安装:
```
pip install requests
pip install bs4
```
代码中,首先要求用户输入要查询的城市,然后构造 URL,发送请求获取 HTML 页面,并使用 BeautifulSoup 库解析 HTML 页面。最后,查找天气信息并打印即可。
写一个代码爬取泉州市15日内的天气信息
好的,可以使用 Python 编写一个爬虫程序来获取泉州市的天气信息。以下是一个示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头,模拟浏览器发送请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
}
# 泉州市天气URL
url = 'http://www.weather.com.cn/weather/101230501.shtml'
# 发送请求并获取网页内容
response = requests.get(url, headers=headers)
html = response.text
# 使用 BeautifulSoup 解析网页内容
soup = BeautifulSoup(html, 'html.parser')
# 获取天气信息列表
weather_list = []
con_list = soup.find_all('div', class_='con')
for con in con_list[1:]:
date = con.find('h1').text
weather = con.find('p', class_='wea').text
temp = con.find('p', class_='tem').find('span').text
weather_list.append((date, weather, temp))
# 打印天气信息列表
for weather in weather_list:
print(weather)
```
上述代码可以获取近15天泉州市的天气信息,并输出到控制台上。注意,如果要获取其他城市的天气信息,只需要将 `url` 变量中的城市代码替换即可。