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

获取LCSC产品链接遇AttributeError错误,请求代码修正

问题修正方案

错误原因

你遇到的AttributeError是因为两个核心问题:

  • 代码里定位元素的逻辑没找到目标标签,返回了None,却强行调用get_text()导致报错
  • 目标link标签的href是属性值,不是文本内容,用get_text()本身就不符合需求

修正后的代码示例

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

# 初始化Chrome浏览器(可替换为你常用的浏览器)
driver = webdriver.Chrome()
try:
    # 替换为目标LCSC产品页面的URL
    driver.get("https://www.lcsc.com/product-detail/xxxxxx.html")
    
    # 显式等待页面加载,确保目标link标签已渲染完成
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, 'link[rel="canonical"][data-n-head="ssr"]'))
    )
    
    # 解析页面源码
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    
    # 精准定位目标link标签
    canonical_link = soup.find('link', attrs={'rel': 'canonical', 'data-n-head': 'ssr'})
    
    # 检查元素是否存在,避免报错
    if canonical_link:
        # 获取href属性值
        target_href = canonical_link.get('href')
        print(target_href.strip())
    else:
        print("未找到符合条件的link标签")
finally:
    # 无论成功失败都关闭浏览器
    driver.quit()

关键修正点

  • 用soup.find()结合attrs参数,精准匹配带rel="canonical"和data-n-head="ssr"的link标签
  • 用get('href')获取属性值,替代错误的get_text()方法
  • 增加元素存在性判断,避免None对象调用方法引发异常
  • 加入Selenium显式等待,解决动态页面渲染导致的元素未加载问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:31:06