首先明确页面层级结构,再通过requests+BeautifulSoup或Scrapy框架逐层抓取。1. 分析URL规律和HTML结构;2. 用requests获取列表页并提取详情链接;3. 遍历链接解析详情内容;4. Scrapy中使用yield Request实现多级跳转;5. 注意设置请求头、间隔、异常处理与反爬策略。
抓取多级页面是Python爬虫中常见的需求,比如从列表页进入详情页、从一级分类跳转到二级分类等。要实现多层级网页数据抓取,关键在于理清页面之间的跳转逻辑,并逐层提取所需信息。下面介绍几种常用方法和实现思路。
在开始编码前,先分析目标网站的页面结构。典型的多级结构如下:

通过浏览器开发者工具查看每层页面的URL规律和HTML结构,确定如何提取链接与数据。
这是最基础也是最灵活的方式。利用requests发送HTTP请求,用BeautifulSoup解析HTML内容。
示例流程:
代码片段示例:
import requests from bs4 import BeautifulSoup第一层:获取列表页中的详情链接
list_url = "https://www./link/ca14cd6c279d15639a51915b4b7917bc" res = requests.get(list_url) soup = BeautifulSoup(res.text, 'html.parser')
detail_urls = [a['href'] for a in soup.select('.news-list a')]
第二层:抓取每个详情页的内容
for url in detail_urls: detail_res = requests.get(url) detail_soup = BeautifulSoup(detail_res.text, 'html.parser') title = detail_soup.find('h1').text content = detailsoup.find('div', class='content').text print(title, content)
对于复杂项目,推荐使用Scrapy框架,它原生支持请求链式调用,适合处理多层级跳转。
核心机制是通过yield scrapy.Request()将解析出的链接作为新请求加入队列,并传递回调函数和元数据。
示例Spider结构:
import scrapyclass MultiLevelSpider(scrapy.Spider): name = 'multilevel' start_urls = ['https://www./link/ca14cd6c279d15639a51915b4b7917bc']
def parse(self, response): # 提取详情页链接 for href in response.css('.news-list a::attr(href)').getall(): yield response.follow(href, self.parse_detail) def parse_detail(self, response): # 解析详情页 title = response.css('h1::text').get() content = response.css('.content::text').get() # 可在此基础上继续跳转至第三层 comment_url = response.css('.comment-link::attr(href)').get() if comment_url: yield response.follow(comment_url, self.parse_comment, meta={'title': title}) def parse_comment(self, response): # 解析评论页,同时获取之前传递的数据 title = response.meta['title'] comments = response.css('.comment p::text').getall() yield { 'title': title, 'comments': comments }4. 注意事项与优化建议
实际抓取过程中需注意以下几点,避免被封IP或数据遗漏:
基本上就这些。掌握页面跳转逻辑,结合合适的工具,就能稳定抓取多级网页数据。关键是分步处理、层层递进,别一次性想把所有逻辑塞进一个函数里。