使用BeautifulSoup、CSS选择器和Pandas DataFrame翻页仅输出第一页求助
问题排查与修复方案
核心问题点
- 原代码仅对首页发起了一次请求并解析,拿到下一页链接后没有发起新请求、生成新的页面对象,自然无法获取后续页面内容
- 下一页判断逻辑错误嵌套在单页的名言遍历循环内,没有设计外层翻页循环来遍历所有可用页面
- 没有设置翻页终止逻辑,无法在无后续页面时自动停止爬取
修正后可运行代码
import requests import bs4 import pandas as pd base_url = 'http://quotes.toscrape.com' current_url = base_url # 初始页为首页 all_quote = [] all_author = [] all_tag = [] # 外层翻页循环,有下一页就一直爬 while current_url: # 每次循环都请求当前页、解析soup res = requests.get(current_url) soup = bs4.BeautifulSoup(res.text,'lxml') # 遍历当前页所有名言 for element in soup.select('.quote'): quote = element.select_one('span.text').text all_quote.append(quote) author = element.select_one('small.author').text all_author.append(author) tag = " , ".join(e.text for e in element.select("a.tag")) all_tag.append(tag) # 单页遍历完成后判断是否有下一页 next_page = soup.select_one('li.next>a') if next_page: current_url = base_url + next_page['href'] else: current_url = None # 无下一页时终止外层循环 df = pd.DataFrame({'all_quote': all_quote,'all_author':all_author, 'all_tag': all_tag}) print(df)
修正说明
- 新增
while外层循环控制翻页逻辑,每次循环都重新请求当前页面、解析生成新的soup对象 - 把下一页判断逻辑从名言遍历循环中移出,放在单页处理完成之后,读取到下一页链接就更新当前请求地址,无下一页就终止循环
- 所有页的名言数据都会统一追加到三个列表中,最后生成的DataFrame包含全站所有页面数据
内容的提问来源于stack exchange,提问作者user16658414
相关产品推荐
相关产品推荐

