首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >列表追加从Beautifulsoup.find_all创建二维列表而不是一维列表。

列表追加从Beautifulsoup.find_all创建二维列表而不是一维列表。
EN

Stack Overflow用户
提问于 2021-10-20 09:54:28
回答 1查看 34关注 0票数 0

我正在解析一个在python中使用漂亮汤的网站,在找到所有元素之后,我想从结果列表中删除数字并将它们添加到列表中:

代码语言:javascript
复制
## find all prices on page
prices = soup.find_all("div", class_="card-footer")
#print(prices)

## extract digits
stripped = [] # declare empty list
for p in prices:
    print(p.get_text(strip=True))
    stripped.append(re.findall(r'\d+', p.get_text(strip=True)))
print(stripped)

结果:

代码语言:javascript
复制
[['555'], ['590'], ['599'], ['1000'], ['5000'], ['5000'], ['9999'], ['10000'], ['12000']]

我要怎么做,才能得到一个一维列表呢?

因为我只需要“剥离”列表,所以除了使用re.findall并在行prices = soup.find_all("div", class_="card-footer")中直接提取数字之外,也许还有更简单的方法来提取数字。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-20 10:02:28

find_all返回一个列表。因此,如果您只对第一个元素感兴趣(在您的情况下可能只有一个元素),那么:

代码语言:javascript
复制
stripped.append(re.findall(r'\d+', p.get_text(strip=True))[0])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69643870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档