gpt4 book ai didi

python - 将标记字符串附加到 BeautifulSoup 中的标记

转载 作者:太空狗 更新时间:2023-10-30 02:19:52 25 4
gpt4 key购买 nike

是否可以将标记设置为标记内容(类似于在 JavaScript 中设置 innerHtml)?

举例来说,假设我想添加 10 <a>元素到 <div> , 但用逗号分隔:

soup = BeautifulSoup(<<some document here>>)

a_tags = ["<a>1</a>", "<a>2</a>", ...] # list of strings
div = soup.new_tag("div")
a_str = ",".join(a_tags)

使用 div.append(a_str)转义 <>进入&lt;&gt; , 所以我最终得到了

<div> &lt;a1&gt; 1 &lt;/a&gt; ... </div>

BeautifulSoup(a_str)将其包装在 <html> 中,我认为将树从中取出是一种不雅的 hack。

怎么办?

最佳答案

您需要从包含链接的 HTML 字符串中创建一个 BeautifulSoup 对象:

from bs4 import BeautifulSoup

soup = BeautifulSoup()
div = soup.new_tag('div')

a_tags = ["<a>1</a>", "<a>2</a>", "<a>3</a>", "<a>4</a>", "<a>5</a>"]
a_str = ",".join(a_tags)

div.append(BeautifulSoup(a_str, 'html.parser'))

soup.append(div)
print soup

打印:

<div><a>1</a>,<a>2</a>,<a>3</a>,<a>4</a>,<a>5</a></div>

替代方案:

为每个链接创建一个标签并将其附加到div。此外,在除最后一个链接之外的每个链接后附加一个逗号:

from bs4 import BeautifulSoup

soup = BeautifulSoup()
div = soup.new_tag('div')

for x in xrange(1, 6):
link = soup.new_tag('a')
link.string = str(x)
div.append(link)

# do not append comma after the last element
if x != 6:
div.append(",")

soup.append(div)

print soup

打印:

<div><a>1</a>,<a>2</a>,<a>3</a>,<a>4</a>,<a>5</a></div>

关于python - 将标记字符串附加到 BeautifulSoup 中的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26984933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com