You need to enable JavaScript to run this app. Python如何实现分页循环爬取指定网页的目标元素
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现分页循环爬取指定网页的目标元素

分页爬取实现方案
  • 先补全请求头模拟浏览器访问,避免被网站反爬拦截
  • 解析第一页的分页区块,提取所有分页链接,自动将相对路径补全为绝对路径,用集合去重避免重复爬取
  • 循环遍历所有分页的URL,逐页提取红圈标注的目标元素
  • 增加异常捕获和请求间隔,避免单个分页失败中断程序,同时防止请求过快被封IP
  • 可根据需要将提取到的结果存入本地文件,无需额外依赖其他库

完整调整后代码

from bs4 import BeautifulSoup
import requests
import time
from urllib.parse import urljoin

# 模拟浏览器请求头,避免被反爬
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}

# 目标初始页
base_url = "http://www.eoechina.com.cn/cn2019/gonggaoxinxi.html?classID=1"
# 存储所有分页URL,自动去重
all_page_urls = set()
all_page_urls.add(base_url)

# 请求初始页提取全部分页链接
first_res = requests.get(base_url, headers=headers, timeout=10)
# 自动适配网站编码,解决乱码问题
first_res.encoding = first_res.apparent_encoding
soup = BeautifulSoup(first_res.content, "html.parser")

# 提取分页区块的链接,选择器根据实际页面分页容器的类名调整
page_links = soup.select("div.pagination a, div.page a, div.fenye a")
for link in page_links:
    href = link.get("href")
    if href:
        full_page_url = urljoin(base_url, href)
        all_page_urls.add(full_page_url)

# 存储爬取到的目标数据
crawled_data = []
# 遍历所有分页爬取目标元素
for page_url in all_page_urls:
    try:
        res = requests.get(page_url, headers=headers, timeout=10)
        res.encoding = res.apparent_encoding
        page_soup = BeautifulSoup(res.content, "html.parser")

        # 提取公告列表的目标元素,选择器根据实际页面公告列表的结构调整
        notice_items = page_soup.select("div.notice_list ul li, table.notice_table tr")
        for item in notice_items:
            title_node = item.select_one("a")
            time_node = item.select_one("span.time, td.time")
            if not title_node:
                continue
            # 提取目标字段:标题、发布时间、详情链接
            title = title_node.get_text(strip=True)
            detail_url = urljoin(page_url, title_node.get("href"))
            pub_time = time_node.get_text(strip=True) if time_node else "未标注发布时间"
            crawled_data.append({
                "标题": title,
                "发布时间": pub_time,
                "详情链接": detail_url
            })
        # 间隔0.5秒再请求下一页,降低服务器压力也避免被封
        time.sleep(0.5)
    except Exception as e:
        print(f"爬取{page_url}失败,错误信息:{e}")
        continue

# 打印爬取结果
for data in crawled_data:
    print(data)

注意事项

  • 代码中标注为需要调整的css选择器(比如分页容器、公告列表的类名),可直接在浏览器中右键检查对应红圈元素、分页区块,复制对应的css选择器替换原有代码中的选择器即可
  • 如果目标页面的分页是前端动态加载的,静态请求拿不到分页链接和内容的话,需要替换为支持浏览器渲染的请求工具再执行爬取
  • 可根据需求导入csv、json等库,将crawled_data直接序列化保存到本地文件

内容的提问来源于stack exchange,提问作者ah bon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.30 15:06:03