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

Python爬虫报'str'无'descendants'属性AttributeError如何解决?

问题原因
  • 核心错误:你直接使用导入时重命名为bs的BeautifulSoup类调用实例方法find_all,并未先实例化BeautifulSoup解析对象。类的实例方法默认第一个参数为实例本身,你直接用类名调用时,传入的第一个参数"div"会被识别为实例参数,方法内部访问该参数的descendants属性时,就会抛出字符串没有对应属性的异常。
  • 仅构造了目标URL,没有发送HTTP请求获取对应页面的HTML内容,缺少解析的源数据。
  • 小问题1:title = title.replace(" ", "+")放在循环内部,第一次循环后空格已经全部替换完成,后续循环的该操作无意义。
  • 小问题2:你定义的p1列表中部分URL的占位符缺了等号,比如https://www.litera.ro/catalogsearch/result/?q{}应该改为https://www.litera.ro/catalogsearch/result/?q={},否则请求其他站点时会出现URL格式错误。
解决方法
  1. 发送GET请求获取目标URL的HTML内容,添加请求头模拟浏览器避免反爬拦截。
  2. 将获取到的HTML文本传入bs()构造BeautifulSoup解析实例,再用该实例调用find_all方法解析节点。
  3. 把空格替换操作移到循环外部,修正p1列表中错误的URL格式。
修复后可运行代码
import requests
from bs4 import BeautifulSoup as bs

# 修正了部分URL缺失的等号
p1 = ["https://www.libris.ro/search?iv.q={}", "https://carturesti.ro/product/search/{}", "https://www.elefant.ro/search?SearchTerm={}&StockAvailability=true", "https://www.litera.ro/catalogsearch/result/?q={}", "https://www.librariadelfin.ro/?submitted=1&O=search&keywords={}&do_submit=1", "https://bookzone.ro/cautare?term={}", "https://www.librex.ro/search/{}/?q={}"]

title = "percy jackson"
# 空格替换移到循环外
title = title.replace(" ", "+")
# 添加请求头模拟浏览器,避免反爬拦截
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}

for x in p1:
    url = x.format(title)
    if url == "https://www.libris.ro/search?iv.q=" + title :
        # 发送请求获取页面内容
        resp = requests.get(url, headers=headers)
        # 自动识别编码避免乱码
        resp.encoding = resp.apparent_encoding
        # 实例化BeautifulSoup对象后再调用查找方法
        soup = bs(resp.text, "html.parser")
        books = soup.find_all("div", class_="product-item-info imgdim-x")
        for each_book in books:
            book_url = each_book.find("a")["href"]
            price = each_book.find("span", class_="price-wrapper").text.strip()
            print(book_url)
            print(price)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:39:01