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

Selenium Python爬取网页已配置启用JS仍提示需开启JavaScript求助

问题原因&解决方案

你遇到的该问题核心不是没有启用JS,是以下几个常见的Selenium爬取动态页面的坑:

  • 你使用的是旧版Chrome无头模式(--headless),该模式的JS渲染逻辑和普通Chrome差异较大,容易被网站判定为未启用JS,或是触发反爬机制
  • 仅设置2秒隐式等待,目标站点是单页应用(SPA),动态内容加载时间不固定,大概率还没完成渲染就提前抓取了页面源码
  • 没有隐藏Selenium的自动化特征,被网站反爬策略识别,故意返回未启用JS的静态页面

修复步骤

  1. 替换旧版无头模式参数为新版无头模式:将options.add_argument("--headless")替换为options.add_argument("--headless=new"),新版无头模式和普通Chrome的行为完全一致
  2. 新增反反爬配置,隐藏Selenium自动化特征
  3. 替换固定时长的隐式等待为显式等待,等待目标内容加载完成后再抓取页面源码
  4. 增加页面加载超时设置,避免网络波动导致加载失败

修复后完整代码

from selenium import webdriver
from selenium.common.exceptions import WebDriverException, TimeoutException
from selenium.webdriver.chrome.service import Service
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

service = Service("/home/ubuntu/selenium_drivers/chromedriver")

options = webdriver.ChromeOptions()
options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.3")
# 替换为新版无头模式
options.add_argument("--headless=new")
options.add_argument('--ignore-certificate-errors')
options.add_argument("--enable-javascript")
options.add_argument('--incognito')
# 新增反反爬参数,隐藏自动化特征
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)

url_list = "https://memphissymphony.secure.force.com/ticket/#/events/a0S3o00001J8qqiEAB"

driver = None
try:
    driver = webdriver.Chrome(service = service, options = options)
    # 隐藏webdriver属性,避免被反爬识别
    driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
    driver.set_page_load_timeout(30)
    driver.get(url_list)
    # 显式等待最多10秒,直到事件详情容器加载完成,可根据实际要抓取的元素修改选择器
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, "event-detail-container"))
    )
    html_content = driver.page_source
except (WebDriverException, TimeoutException) as e:
    print(f"加载出错: {e}")
finally:
    if driver:
        driver.quit()
    
soup = BeautifulSoup(html_content, 'html.parser')
print(soup)

可选调试方案

如果调整后还是无法拿到内容,可以把显式等待的元素选择器替换为你实际要抓取的内容对应的标签类名,也可以临时去掉无头模式,打开浏览器窗口直观查看页面加载情况,确认是否有其他验证拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:45:04