python爬虫爬取一年中每个季度的数据
时间: 2023-12-22 20:27:55 浏览: 33
以下是使用Python爬虫爬取北京市2020年GDP每个季度数据的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://tjj.beijing.gov.cn/tjsj_31433/yjdsj_31440/gdp_31750/2020/index.html'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 获取每个季度的数据所在的tr标签
quarter_trs = soup.find_all('tr', class_='m_bg1')
# 遍历每个季度的tr标签,获取数据
for tr in quarter_trs:
tds = tr.find_all('td')
quarter = tds[0].text.strip() # 季度
gdp = tds[1].text.strip() # GDP
print(quarter, gdp)
```
解释一下代码:
首先,我们使用requests库向目标网站发送请求,并使用BeautifulSoup库解析响应的HTML文档。
然后,我们使用find_all()方法找到每个季度的数据所在的tr标签,并遍历每个tr标签,使用find_all()方法获取每个tr标签下的td标签,从而获取季度和GDP数据。
最后,我们将季度和GDP数据打印出来。
相关问题
写一个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股数据,并将其打印出来。
python爬虫爬取旅游数据
以下是使用Python爬虫爬取旅游数据的一般步骤:
1. 寻找目标网站并分析其网页结构,确定需要爬取的数据类型和数据存放位置。
2. 使用Python中的requests库向目标网站发送请求,获取网页源代码。
3. 使用Python中的BeautifulSoup库解析网页源代码,提取需要的数据。
4. 将提取的数据存储到本地文件或数据库中。
下面是一个简单的示例,演示如何使用Python爬虫爬取携程网站的旅游数据:
```python
import requests
from bs4 import BeautifulSoup
# 发送请求,获取网页源代码
url = 'https://you.ctrip.com/sight/china110000.html'
response = requests.get(url)
html = response.text
# 解析网页源代码,提取需要的数据
soup = BeautifulSoup(html, 'html.parser')
sight_list = soup.find_all('div', class_='list_mod2')
for sight in sight_list:
name = sight.find('div', class_='rdetailbox').find('a').text
address = sight.find('p', class_='address color999').text
score = sight.find('span', class_='score').text
print(name, address, score)
# 将提取的数据存储到本地文件或数据库中
# 这里只是简单地输出到控制台
```