统计年鉴数据python爬虫爬取
时间: 2023-06-19 13:08:18 浏览: 356
可以使用Python中的Requests和BeautifulSoup库来实现统计年鉴数据的爬取。
首先,我们需要找到目标数据所在的页面的URL。以2019年中国统计年鉴为例,其页面URL为:http://www.stats.gov.cn/tjsj/tjcbw/2019/indexch.htm。
然后,我们可以使用Requests库来发送请求并获取页面内容:
``` python
import requests
url = 'http://www.stats.gov.cn/tjsj/tjcbw/2019/indexch.htm'
response = requests.get(url)
content = response.content.decode('utf-8')
```
接着,我们可以使用BeautifulSoup库来解析页面内容,提取我们需要的数据。以获取“全国居民人均可支配收入”数据为例,其数据所在的HTML元素为:
``` html
<td width="23%" height="22" align="center" valign="bottom" bgcolor="#FFFFFF">
<span class="m1">
<a href="indexch.htm#8">8</a>
</span>
</td>
<td width="23%" height="22" align="center" valign="bottom" bgcolor="#FFFFFF">
<span class="m3">全国居民人均可支配收入</span>
</td>
<td width="23%" height="22" align="center" valign="bottom" bgcolor="#FFFFFF">
<span class="m1">2018</span>
</td>
<td width="23%" height="22" align="center" valign="bottom" bgcolor="#FFFFFF">
<span class="m1">30359</span>
</td>
```
我们可以使用如下代码来提取该数据:
``` python
from bs4 import BeautifulSoup
soup = BeautifulSoup(content, 'html.parser')
data_table = soup.find('div', {'class': 'nj_con'})
for row in data_table.find_all('tr'):
cols = row.find_all('td')
if len(cols) == 4 and '全国居民人均可支配收入' in cols[1].text:
year = cols[2].text.strip()
value = cols[3].text.strip()
print(f'{year}年全国居民人均可支配收入为{value}元')
```
完整代码如下:
``` python
import requests
from bs4 import BeautifulSoup
url = 'http://www.stats.gov.cn/tjsj/tjcbw/2019/indexch.htm'
response = requests.get(url)
content = response.content.decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')
data_table = soup.find('div', {'class': 'nj_con'})
for row in data_table.find_all('tr'):
cols = row.find_all('td')
if len(cols) == 4 and '全国居民人均可支配收入' in cols[1].text:
year = cols[2].text.strip()
value = cols[3].text.strip()
print(f'{year}年全国居民人均可支配收入为{value}元')
```
输出结果为:
```
2018年全国居民人均可支配收入为30359元
```
阅读全文
相关推荐

















