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

Scrapy报错'str object has no attribute css'的解决方法咨询

Scrapy Shell 报错修复方案

问题核心:你用response.css('.article-main').getall()拿到的是字符串列表,字符串本身没有.css()方法,所以调用Art.css(...)会触发str object has no attribute css错误。

解决方法

方法1:直接链式选择(推荐)

不需要单独提取.article-main,直接嵌套选择器定位目标文本:

# 获取第一个.article-main下的.art2-amp文本
target_text = response.css('.article-main:first-child .art2-amp::text').get()
# 如果要获取所有.article-main下的对应文本,用getall()
all_target_texts = response.css('.article-main .art2-amp::text').getall()

方法2:保留Selector对象而非转成字符串

如果需要先处理.article-main的Selector对象,不要用getall(),直接保留css()返回的SelectorList:

# 拿到Selector对象列表(而非字符串)
articles = response.css('.article-main')
# 取第一个Selector对象
art = articles[0]
# 调用css方法提取文本
target_text = art.css('.art2-amp::text').get()

额外注意点

  • 代码里的中文引号(‘’)要改成英文引号(''或""),否则会触发语法错误
  • Python内置函数是小写len(),不是Len()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 18:39:51