写一个python爬虫爬取新乡天气数据
时间: 2023-12-22 17:46:57 浏览: 30
以下是一个简单的Python爬虫示例,用于获取天气数据:
```python
import requests
from bs4 import BeautifulSoup
# 目标URL
url = 'http://www.weather.com.cn/weather/101180301.shtml'
# 发送HTTP请求,并获取响应内容
response = requests.get(url)
html = response.content
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(html, 'html.parser')
# 获取天气信息
weather_info = soup.find('div', {'class': 't'}).text.strip()
# 输出天气信息
print('新乡市天气:', weather_info)
```
执行以上代码,将输出类似以下的结果:
```
新乡市天气: 晴转多云
```
请注意,上述代码仅仅是一个示例,实际的爬虫需要更多的处理和优化,以确保能够正确地获取所需的数据。同时,爬虫应该尽可能地遵守网站的使用规定,不要频繁地发送请求或者使用过于复杂的算法,以避免对目标网站造成不必要的负担或者违反相关法规。
相关问题
python爬虫爬取一年天气数据
以下是使用Python爬虫爬取一年天气数据的示例代码:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
def get_weather_data(year):
# 创建一个空的DataFrame用于保存数据
weather_data = pd.DataFrame(columns=['日期', '天气', '最高温度', '最低温度'])
# 循环遍历每个月份
for month in range(1, 13):
# 构造URL
url = f'http://www.weather.com.cn/weather/{year}{month:02d}.shtml'
# 发送HTTP请求获取页面内容
response = requests.get(url)
response.encoding = 'utf-8'
html = response.text
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(html, 'html.parser')
# 获取每天的天气数据
days = soup.select('.t li')
# 循环遍历每天的数据
for day in days:
date = day.select('.time')[0].text.strip()
weather = day.select('.wea')[0].text.strip()
high_temp = day.select('.tem span')[0].text.strip()
low_temp = day.select('.tem i')[0].text.strip()
# 将数据添加到DataFrame中
weather_data = weather_data.append({'日期': date, '天气': weather, '最高温度': high_temp, '最低温度': low_temp}, ignore_index=True)
return weather_data
# 调用函数获取2021年的天气数据
weather_data_2021 = get_weather_data(2021)
# 打印结果
print(weather_data_2021)
```
写一个Python爬虫爬取a股数据
好的,以下是一个简单的Python爬虫代码,可以爬取A股数据:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://quote.eastmoney.com/center/gridlist.html#hs_a_board'
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.text, 'html.parser')
table = soup.find('table', {'id': 'table_wrapper-table'})
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
for col in cols:
print(col.text.strip(), end='\t')
print()
```
这个爬虫会爬取东方财富网的A股数据,并将其打印出来。