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

Kon*_*rad 4 python string markup beautifulsoup html-parsing

是否可以将标记设置为标记内容(类似于innerHtmlJavaScript中的设置)?

举个例子,假设我想在a中添加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)
Run Code Online (Sandbox Code Playgroud)

使用div.append(a_str)逃逸<和>成&lt;和&gt;,所以我结束了

<div> &lt;a1&gt; 1 &lt;/a&gt; ... </div>
Run Code Online (Sandbox Code Playgroud)

BeautifulSoup(a_str)把它包裹起来<html>,我看到把树当作一个不雅的黑客.

该怎么办?

ale*_*cxe 7

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

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
Run Code Online (Sandbox Code Playgroud)

打印:

<div><a>1</a>,<a>2</a>,<a>3</a>,<a>4</a>,<a>5</a></div>
Run Code Online (Sandbox Code Playgroud)

替代方案:

对于每个链接创建一个Tag并附加到它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
Run Code Online (Sandbox Code Playgroud)

打印:

<div><a>1</a>,<a>2</a>,<a>3</a>,<a>4</a>,<a>5</a></div>
Run Code Online (Sandbox Code Playgroud)