【问题标题】:Python BS4 Sort HTML in alphabetical order?Python BS4 按字母顺序对 HTML 进行排序?
【发布时间】:2022-10-07 19:07:56
【问题描述】:
如何将 html 代码按字母顺序排序?
from bs4 import BeautifulSoup
html = \'\'\'[<div>Red </div>, <div>Green </div>, <div>Orange </div>, <div>Blue </div>]\'\'\'
soup = BeautifulSoup(html, \'html.parser\')
paints = soup.findAll(\"div\")
print(str(paints).strip(\'[]\'))
输出:
<div>Red </div>, <div>Green </div>, <div>Orange </div>, <div>Blue </div>
想要的输出:
<div>Blue </div>, <div>Green </div>, <div>Red </div>, <div>Orange </div>
标签:
python
html
sorting
beautifulsoup
【解决方案1】:
只需在代码中添加sorted 函数并使用key 使用get_text() 方法从标签中排序为文本,它将根据需要返回数据。
sorted(paints, key=lambda x: x.get_text())
输出:
[<div>Blue </div>, <div>Green </div>, <div>Orange </div>, <div>Red </div>]
【解决方案2】:
您的预期输出不是字母 - 无论如何尝试迭代字母并检查您的元素文本是否以字符开头。
例子
from bs4 import BeautifulSoup
import string
html = '''[<div>Red </div>, <div>Green </div>, <div>Orange </div>, <div>Blue </div>]'''
sorted_html_tags =[]
soup = BeautifulSoup(html, 'html.parser')
for c in string.ascii_lowercase:
for e in soup.find_all("div"):
if e.text.lower().startswith(c):
sorted_html_tags.append(e)
sorted_html_tags
输出
[<div>Blue </div>, <div>Green </div>, <div>Orange </div>, <div>Red </div>]