爬取https://gdzd.stats.gov.cn/sjfb/sjjd/每一页的标题,加上翻页程序
时间: 2024-11-22 19:46:25 浏览: 24
爬取网站页面的标题并实现翻页功能通常需要使用网络爬虫技术,例如Python中的BeautifulSoup和Scrapy库。这里是一个简化的步骤概述:
1. **安装必要的库**:
首先,你需要安装`requests`, `beautifulsoup4`以及可能的`lxml`库(如果使用BeautifulSoup4),可以使用以下命令安装:
```bash
pip install requests beautifulsoup4
```
2. **编写基本的爬虫脚本**:
使用`requests`获取网页内容,然后解析HTML内容找到标题。这是使用BeautifulSoup的基本示例:
```python
import requests
from bs4 import BeautifulSoup
def get_page_titles(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
titles = [title.text for title in soup.select('h1, h2, h3')] # 根据实际网页结构修改选择器
return titles
url_template = "https://gdzd.stats.gov.cn/sjfb/sjjd/{page}"
page = 1
while True:
titles = get_page_titles(url_template.format(page=page))
print(f"Page {page} titles: {titles}")
# 添加翻页逻辑,比如检查下一页链接是否存在
next_page_link = soup.select_one('a[rel="next"]') # 假设下一页链接在'a'标签且有'rel="next"'
if not next_page_link or 'disabled' in next_page_link['class']:
break # 如果没找到下一页或它不可用,停止爬取
page += 1
```
3. **处理翻页**:
找到页面底部的分页链接,通常通过CSS类、属性或关系属性判断。在这个例子中,假设每个分页链接都有`rel="next"`:
```python
next_page_link = soup.select_one('a[rel="next"]')
if next_page_link:
next_url = next_page_link['href']
# 更新URL继续爬取
else:
break
```
注意:实际操作时,你需要根据目标网站的具体HTML结构来调整选择器(如`select`部分)。并且,遵守网站的robots.txt规则,并尊重其爬虫政策。
阅读全文