python爬取天气网泉州七天预报 代码
时间: 2023-06-06 15:07:05 浏览: 53
请看以下Python代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.tianqi.com/quanzhou/'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
forecast = soup.find_all("div", {"class": "day"})
for day in forecast:
date = day.find("p", {"class": "day-time"}).text
weather = day.find("p", {"class": "wea"}).text
temperature = day.find("p", {"class": "tem"}).text
wind = day.find("p", {"class": "win"}).text
print(date, weather, temperature, wind)
```
使用requests库获取网页HTML代码,然后使用BeautifulSoup库解析html代码。通过提取HTML中预报的信息,然后使用循环打印出每天的天气预报,包括日期、天气、温度和风向。
相关问题
python爬取天气预报代码
以下是一个简单的Python爬取天气预报的代码示例:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.weather.com.cn/weather/101010100.shtml'
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)
soup = BeautifulSoup(response.content, 'html.parser')
weather_list = soup.select('.t li')
for weather in weather_list:
date = weather.select('.time')[0].text
detail = weather.select('.detail')[0].text
temperature = weather.select('.tem')[0].text
print(date, detail, temperature)
```
这个代码使用requests库和BeautifulSoup库来获取天气预报页面,并从页面中提取出日期、天气详情和温度信息。你可以根据自己的需要修改代码来获取更多的信息。
python爬取天气预报
要爬取天气预报,可以使用Python中的第三方库,如requests、BeautifulSoup等等。以下是一个简单的爬取天气预报的示例:
``` python
import requests
from bs4 import BeautifulSoup
# 爬取天气预报网页
url = 'http://www.weather.com.cn/weather/101010100.shtml'
response = requests.get(url)
response.encoding = 'utf-8'
html = response.text
# 解析网页内容
soup = BeautifulSoup(html, 'html.parser')
weather_div = soup.find_all('div', class_='today')
date = weather_div[0].find('h1').string
temperature = weather_div[0].find_all('p')[0].string
description = weather_div[0].find_all('p')[1].string.strip()
# 打印天气预报
print('日期:', date)
print('温度:', temperature)
print('天气:', description)
```
在这个示例中,我们使用requests库获取天气预报的网页内容,并用BeautifulSoup库解析HTML文件。然后,我们使用find_all()方法找到天气预报的相关信息,并将信息打印到屏幕上。
需要注意的是,由于天气预报网站的HTML代码可能会发生变化,以上示例可能需要根据具体情况进行修改。