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

如何解决BeautifulSoup4爬取指定class的a标签返回空列表问题?

问题:无法爬取目标分页标签

想要从https://webtoon-tr.com/webtoon/爬取带有class="last"的<a>标签(示例标签如下):

<a class="last" aria-label="Last Page" href="https://webtoon-tr.com/webtoon/page/122/">Son »</a>

但使用以下BeautifulSoup代码时,soup.find_all("a",{"class":"last"})返回空列表,且爬取所有<a>标签仅得到2个无关结果:

from bs4 import BeautifulSoup
import requests

url = "https://webtoon-tr.com/webtoon/"
html = requests.get(url).content
soup = BeautifulSoup(html,"html.parser")

last = soup.find_all("a",{"class":"last"})
print(last)

解决方案

原因分析

出现这个问题大概率是以下两个原因之一:

  • 请求被识别为爬虫:网站会根据请求头判断请求来源,无User-Agent的请求可能被返回简化版内容。
  • 内容动态渲染:目标分页标签是通过JavaScript动态加载的,requests只能获取服务器返回的初始HTML,无法获取JS加载后的内容。

方法1:添加请求头模拟浏览器

先尝试给requests添加浏览器标识的请求头,很多情况下可以解决问题:

from bs4 import BeautifulSoup
import requests

url = "https://webtoon-tr.com/webtoon/"
# 模拟Chrome浏览器的请求头
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"
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")

last_page_link = soup.find("a", class_="last")
if last_page_link:
    print(f"最后一页链接:{last_page_link['href']}")
else:
    print("未找到目标标签")

方法2:使用浏览器渲染工具(处理动态内容)

如果添加请求头后仍然无法获取目标标签,说明内容是动态加载的,需要用Selenium模拟浏览器加载页面:

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

url = "https://webtoon-tr.com/webtoon/"
# 配置无头浏览器模式(不弹出浏览器窗口)
chrome_options = Options()
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--disable-gpu")

# 初始化浏览器并加载页面
driver = webdriver.Chrome(options=chrome_options)
driver.get(url)

# 获取动态加载后的页面源码
page_source = driver.page_source
soup = BeautifulSoup(page_source, "html.parser")

last_page_link = soup.find("a", class_="last")
if last_page_link:
    print(f"最后一页链接:{last_page_link['href']}")
else:
    print("未找到目标标签")

# 关闭浏览器
driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:18:26