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

使用requests+BeautifulSoup抓取静态网页data-component-props时触发TypeError

问题

使用requests+BeautifulSoup爬取udemy首页,目标是获取类名为ud-component--logged-out-home--logged-out-home的元素的data-component-props属性值(该内容为静态,页面源码可见),但运行代码时触发TypeError错误。

报错代码

import requests
from bs4 import BeautifulSoup

link = "https://www.udemy.com/"

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9,bn;q=0.8'
}

with requests.Session() as s:
    s.headers.update(headers)
    res = s.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    container = soup.select_one("[class='ud-component--logged-out-home--logged-out-home']")['data-component-props']
    print(container)
解决方案

错误原因

TypeError的核心原因是soup.select_one()没有匹配到目标元素,返回了None,此时尝试通过['data-component-props']取属性就会触发类型错误。常见触发场景:

  • 请求头不足以绕过反爬,udemy返回了无目标元素的页面(如验证页)
  • 页面类名已更新,原选择器失效

修复步骤

  1. 验证请求返回内容:打印res.text确认返回的页面源码中是否存在目标类名和属性,判断是否是反爬导致内容缺失。如果是反爬,可补充cookie等请求头字段(从浏览器开发者工具复制)。
  2. 增加异常判断:在取属性前先检查元素是否存在,避免直接取值报错。
  3. 调整选择器:如果类名更新,通过浏览器开发者工具重新定位目标元素的选择器。

修复后代码示例

import requests
from bs4 import BeautifulSoup

link = "https://www.udemy.com/"

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9,bn;q=0.8'
}

with requests.Session() as s:
    s.headers.update(headers)
    res = s.get(link)
    print(f"请求状态码: {res.status_code}")
    soup = BeautifulSoup(res.text,"lxml")
    container_element = soup.select_one("[class='ud-component--logged-out-home--logged-out-home']")
    
    if container_element:
        data_props = container_element.get('data-component-props')
        print(data_props)
    else:
        print("未找到目标元素,请检查请求内容或选择器是否正确")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:23:13