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

如何用Python获取英雄联盟故事页<div id="App">内的动态内容?

解决客户端JS渲染页面的抓取问题

你猜的没错,这就是客户端JavaScript渲染导致的问题:requests只会获取服务器返回的初始静态HTML,而页面里的核心内容是浏览器加载后通过JS动态生成的,所以直接爬不到填充后的#App内容。要拿到渲染后的完整HTML,得用能模拟浏览器执行JS的工具,下面给你两种可行的Python实现方案:

方案一:使用Selenium

Selenium可以模拟真实浏览器的行为,自动执行JS并加载完整页面。

  1. 先安装依赖:
pip install selenium

另外需要下载对应浏览器的驱动(比如ChromeDriver),确保驱动版本和你的浏览器版本匹配,把驱动放到系统PATH里或者在代码里指定路径。

  1. 示例代码:
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://universe.leagueoflegends.com/es_ES/explore/short-stories/oldest/"

# 启动Chrome浏览器(也可以换成Firefox等)
driver = webdriver.Chrome()
driver.get(URL)

# 等待页面关键元素加载完成,避免拿到不完整内容
# 这里等待短篇故事卡片元素出现,可根据实际页面结构调整选择器
try:
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, "StoryCard"))
    )
except:
    pass  # 超时也继续,至少获取当前已加载内容

# 获取渲染后的完整页面源码
html = driver.page_source
driver.quit()  # 关闭浏览器

# 用BeautifulSoup解析内容
soup = BeautifulSoup(html, "html.parser")
app_div = soup.find("div", id="App")
# 后续提取故事链接等操作...

方案二:使用Playwright

Playwright是微软推出的自动化工具,API更简洁,内置浏览器驱动,无需手动下载。

  1. 安装依赖:
pip install playwright
playwright install chromium
  1. 示例代码:
from playwright.sync_api import sync_playwright
from bs4 import BeautifulSoup

URL = "https://universe.leagueoflegends.com/es_ES/explore/short-stories/oldest/"

with sync_playwright() as p:
    # 启动无头浏览器(headless=True为无界面模式,改成False可显示浏览器窗口)
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()
    page.goto(URL)
    
    # 等待页面加载完成,指定元素出现后再获取内容
    page.wait_for_selector(".StoryCard", timeout=10000)
    
    # 获取完整页面源码
    html = page.content()
    browser.close()

# 解析内容
soup = BeautifulSoup(html, "html.parser")
app_div = soup.find("div", id="App")
# 后续处理...

两种方案都能拿到浏览器渲染后的完整HTML,之后你就可以从中提取短篇故事的链接,再逐个进入页面抓取文本内容了。

内容的提问来源于stack exchange,提问作者Alberto Salazar Lloreda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:50:34