AttributeError: ResultSet object has no attribute 'get_text'. You're probably treating a list of elements like a single element

删除回忆录丶 提交于 2021-02-11 16:41:30

问题


I got the following list of lists from parsing with Bs4 through the snippet:

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>]]

The point is that not every nested list has exactly the same content nor the same length, so I don't want to simplify getting the text in a sole list.

I've tried this code:

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

But as I told it yields the following output:

[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]

While the expected ouput is:

[[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]]

Any help?


回答1:


try this

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


来源:https://stackoverflow.com/questions/60592456/attributeerror-resultset-object-has-no-attribute-get-text-youre-probably-tr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!