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

使用BeautifulSoup爬取LSE课程代码时遇NonType错误求解决方案

解决爬取LSE课程代码的NonType错误问题

错误原因

你遇到的NonType错误是因为soup.find("div", attrs={'class': "courseList"})没找到目标元素,返回了None,后续调用find_all自然会触发报错。核心问题有两个:

  • 页面内容可能是JavaScript动态渲染的,直接用requests获取的原始HTML里没有courseList这类元素
  • 你用的class选择器包含动态生成的随机类名(比如sc-esYiGF ikRlqb),这类类名会随页面刷新变化,导致选择器失效

可行爬取代码

方案1:静态解析+稳定选择器

如果页面是静态渲染的,直接跳过不稳定的动态类名,定位最直接的目标元素:

import requests
from bs4 import BeautifulSoup

url = "https://www.lse.ac.uk/study-at-lse/undergraduate/bsc-finance?year=9a9aaf13-af33-47f6-9150-8eabe38f0aa8"
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")

# 直接定位所有class为code的元素,跳过动态类名
course_codes = soup.find_all("div", class_="code")
for code in course_codes:
    print(code.get_text(strip=True))

方案2:处理动态加载页面(用Selenium)

如果页面是动态渲染的,requests拿不到完整内容,需要用浏览器渲染工具获取:

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.lse.ac.uk/study-at-lse/undergraduate/bsc-finance?year=9a9aaf13-af33-47f6-9150-8eabe38f0aa8"

# 初始化Chrome浏览器(需提前安装ChromeDriver)
driver = webdriver.Chrome()
driver.get(url)

try:
    # 等待课程代码元素加载完成
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, "code"))
    )
    # 获取渲染后的完整页面HTML
    page_source = driver.page_source
    soup = BeautifulSoup(page_source, "html.parser")
    
    # 提取所有课程代码
    course_codes = soup.find_all("div", class_="code")
    for code in course_codes:
        print(code.get_text(strip=True))
finally:
    driver.quit()

关键注意事项

  • 绝对不要用带随机字符的动态类名做选择器,这类类名是前端框架自动生成的,页面刷新就会失效
  • 必须添加User-Agent请求头,避免被网站识别为爬虫拦截
  • 动态页面只能用浏览器渲染工具获取完整内容,静态解析工具拿不到JS加载的内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 17:52:33