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

如何使用BeautifulSoup提取页面中的active、on、total数值

解决BeautifulSoup无法提取JS生成的active/on/total数值问题

你遇到的核心问题是目标HTML内容由JavaScript动态生成,直接用BeautifulSoup爬取初始HTTP返回的页面时,这段包含<span>的代码还未被渲染生成,所以find_all('span')找不到任何元素。

以下是两种可行的解决方案:

方案1:直接从JavaScript代码中提取数值

如果页面的JavaScript代码里直接定义了active、on、total的数值,可以通过正则表达式从JS代码中提取,无需启动浏览器,速度更快:

import re
from bs4 import BeautifulSoup

# 假设response.text是你请求页面得到的原始内容
soup = BeautifulSoup(response.text, 'html.parser')

# 遍历所有script标签,找到包含目标JS逻辑的标签
for script in soup.find_all('script'):
    if not script.string:
        continue
    js_content = script.string
    # 检查是否包含目标数值拼接逻辑
    if 'active + \'/\' + on + \'/\' + total' in js_content:
        # 提取三个变量的数值(假设变量为数字类型,直接赋值)
        active_match = re.search(r'var\s+active\s*=\s*(\d+);', js_content)
        on_match = re.search(r'var\s+on\s*=\s*(\d+);', js_content)
        total_match = re.search(r'var\s+total\s*=\s*(\d+);', js_content)
        
        if active_match and on_match and total_match:
            print(f"active: {active_match.group(1)}, on: {on_match.group(1)}, total: {total_match.group(1)}")
            break

方案2:用无头浏览器渲染页面后解析

如果active、on、total是通过复杂JS逻辑动态计算生成的,需要先让浏览器执行JS渲染页面,再获取最终HTML解析:

以Selenium为例(需先安装Selenium及对应浏览器驱动):

from selenium import webdriver
from bs4 import BeautifulSoup

# 配置无头Chrome浏览器
options = webdriver.ChromeOptions()
options.add_argument('--headless=new')
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=options)

# 访问目标页面
driver.get('你的目标页面URL')

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

# 定位目标span并提取数值
target_span = soup.find('span', style='font-size: 45px')
if target_span:
    num_text = target_span.get_text(strip=True)
    active_val, on_val, total_val = num_text.split('/')
    print(f"active: {active_val}, on: {on_val}, total: {total_val}")

# 关闭浏览器
driver.quit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:15:11