You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup按类选择元素失败,仅返回目录标题求助

解决Perlego书籍目录爬取问题

问题背景

想要爬取Perlego平台上《getting started with python》书籍页面的目录内容(从Title Page到other books you may like),通过浏览器审查元素找到了目标目录对应的标签类,但使用requests+BeautifulSoup爬取时,仅能获取到目录容器的空结构,无法找到sc-b81fc1ca-2类的标签,返回空列表。

问题原因

Perlego的目录内容是通过JavaScript动态渲染加载的,requests库只能获取页面初始的静态HTML,无法执行页面中的JS代码,因此目标目录元素在初始响应中并不存在。

解决方案

方法1:使用Selenium模拟浏览器渲染页面

Selenium可以模拟真实浏览器的行为,等待页面JS渲染完成后再提取内容:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup

url = "https://www.perlego.com/book/921329/getting-started-with-python-understand-key-data-structures-and-use-python-in-objectoriented-programming-pdf?queryID=9315f2c9285af80efdc99eaa9c5621bc&index=prod_BOOKS&gridPosition=2"

# 初始化Chrome浏览器(需提前安装对应版本的chromedriver)
driver = webdriver.Chrome()
driver.get(url)

# 等待目录容器加载完成,优先用data-testid这类稳定属性定位
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.DATA_TEST_ID, "table-of-contents")))

# 获取渲染后的完整页面源码
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')

# 提取目标目录标签,若动态类名失效可改用标签层级定位
toc_items = soup.find_all(class_='sc-b81fc1ca-2')
for item in toc_items:
    print(item.get_text(strip=True))

driver.quit()

方法2:抓取动态加载的API接口

通过浏览器开发者工具定位返回目录的API接口,直接请求获取结构化数据:

  1. 打开浏览器开发者工具(F12),切换到「网络」面板
  2. 刷新书籍页面,筛选XHR请求,找到包含toc或table-of-contents关键词的请求
  3. 复制该请求URL,用requests直接请求并解析:
import requests

# 替换为实际找到的API接口URL
api_url = "https://www.perlego.com/api/v1/book/921329/toc"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
    # 若需登录验证,需添加对应的Cookie请求头
}

response = requests.get(api_url, headers=headers)
toc_data = response.json()

# 根据实际返回的JSON结构遍历提取标题
for item in toc_data.get("items", []):
    print(item.get("title"))

注意事项

  • 动态生成的类名(如sc-b81fc1ca-2)可能随网站更新变化,建议优先使用data-testid、标签层级等稳定定位方式
  • Perlego存在反爬机制,请求时需设置合理的User-Agent,避免频繁请求,必要时需处理登录验证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:33:49