【问题标题】:AttributeError: ResultSet object has no attribute 'get_text'. You're probably treating a list of elements like a single elementAttributeError:ResultSet 对象没有属性“get_text”。您可能将元素列表视为单个元素
【发布时间】:2020-03-08 21:56:35
【问题描述】:

我通过 sn-p 用 Bs4 解析得到以下列表:

details = [i.find_all('span', {'class':re.compile('item')}) for i in cars]
[[<span class="item">Red <small>col.</small></span>,
  <span class="item">120 <small>cc.</small></span>,
  <span class="item">Available <small>in four days</small></span>,
  <span class="item"><small class="txt-highlight-red">15 min</small></span>],
 [<span class="item">Blue <small>col.</small></span>,
  <span class="item">200 <small>cc.</small></span>,
  <span class="item">Available <small>in a week</small></span>,
  <span class="item">04 mar <small></small></span>],
 [<span class="item">Green <small>col.</small></span>,
  <span class="item">Available <small>immediately</small></span>,
  <span class="item"><small class="txt-highlight-red">2 hours</small></span>]]

关键是不是每个嵌套列表都具有完全相同的内容或相同的长度,所以我不想简化将文本放在一个单独的列表中。

我试过这段代码:

bobo = []
for detail in details:
    for i in detail:
        bobo.append(i.text)

但正如我所说,它会产生以下输出:

[Red col., 120 cc., Available in four days, 15 min., Blue col., 200 cc., Available in a week, 04 mar , Green col., Available immediately, 2 hours]

而预期的输出是:

[[Red col., 120 cc., Available in four days, 15 min.],
[Blue col., 200 cc., Available in a week, 04 mar ],
[Green col., Available immediately, 2 hours]]

有什么帮助吗?

【问题讨论】:

  • 这样可以吗? [i.text for i in cars]。您还应该发布源 HTML。

标签: python-3.x beautifulsoup


【解决方案1】:

试试这个

bobo = []
for detail in details:
    result = []
    for i in detail:
        result.append(i.text)
    bobo.append(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2011-06-15
    • 1970-01-01
    相关资源
    最近更新 更多