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

Python3.7下BeautifulSoup的soup.find报错:find()不接受关键字参数

解决BeautifulSoup find() 报错的问题

我来帮你梳理下代码里的几个问题,逐个修正就能搞定这个报错:

1. 未正确初始化BeautifulSoup解析对象

你当前代码里的 soup = response.read() 只是把网页内容读取成了字节流,并没有转换成BeautifulSoup的解析对象。字节串自带的find()方法和BeautifulSoup的find()完全不是一回事,这是导致报错的核心原因。

正确的做法是把读取到的内容传入BeautifulSoup构造函数,同时指定解析器(比如html.parser):

soup = BeautifulSoup(response.read(), 'html.parser')

2. attrs 参数的语法错误

你写的 attrs ={"class=": "productdescriptionname"} 里,键名多了个多余的等号,应该是"class"而不是"class="。正确的写法是:

attrs={"class": "productdescriptionname"}

3. 查找的标签类型错误

从你提供的HTML结构来看,productdescriptionname是<span>标签的类名,而不是<h4>标签的。所以你应该查找<span>标签,而非<h4>。

修正后的完整代码

import urllib.request
from bs4 import BeautifulSoup

url = "https://link"
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
urlwithagent = urllib.request.Request(url, headers={'User-Agent': user_agent})

response = urllib.request.urlopen(urlwithagent)
# 正确初始化BeautifulSoup解析对象
soup = BeautifulSoup(response.read(), 'html.parser')
# 查找带有指定类名的span标签
product = soup.find("span", attrs={"class": "productdescriptionname"})

# 如果找到目标元素,打印其文本内容;否则提示未找到
if product:
    print(product.get_text().strip())
else:
    print("未找到目标元素")

如果只需要标签里的文字内容,用product.get_text().strip()可以去掉多余的空白字符,比直接打印整个标签对象更实用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:44:40