如何用靓汤返回列表制作一个新的html?

2024-10-08 18:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

soup.find\u all('a')函数将返回一个列表

例如

'''
> # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
> #  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
> #  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
'''

我想用这个列表来制作一个html文件

如果我使用for循环,它将只显示一个字符

还有什么可以列成清单的吗

'''
> # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
> # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
> # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
'''

删除[,之后的</a>]


Tags: comidhttp列表examplesisterclasshref
1条回答
网友
1楼 · 发布于 2024-10-08 18:24:18

只需将其作为字符串输出并将其连接起来:

from bs4 import BeautifulSoup

html = '''<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>'''

soup = BeautifulSoup(html, 'html.parser')
alpha = soup.find_all('a')

to_html = ''.join(str(a) for a in alpha)
print (to_html)

''.join()基本上是这样做的:

# Initialize a variable that is an empty string
to_html = ''

# Iterate through that list
for a in alpha:
   #join the to_html string with a as a string
    to_html = to_html + str(a)

相关问题 更多 >

    热门问题