美丽的汤附加

时间:2018-06-12 09:38:21

标签: python beautifulsoup

我不明白为什么这不起作用。

soup_main = BeautifulSoup('<html><head></head><body><a>FooBar</a></body></html>')
soup_append = BeautifulSoup('<html><head></head><body><a>Meh</a></body></html>')
soup_main.body.append(soup_append.a)

我收到以下错误:

Traceback (most recent call last):File "<stdin>", line 1, in <module>
File "C:\Python34\lib\site-packages\bs4\element.py", line 378, in append
self.insert(len(self.contents), tag)
File "C:\Python34\lib\site-packages\bs4\element.py", line 312, in insert
raise ValueError("Cannot insert None into a tag.")
ValueError: Cannot insert None into a tag.

如果我能理解正在发生的事情,我会很高兴。

1 个答案:

答案 0 :(得分:1)

试试这个:

soup_main = BeautifulSoup('<html><head></head><body><a>FooBar</a></body></html>', 'html.parser')
soup_append = BeautifulSoup('<html><head></head><body><a>Meh</a></body></html>', 'html.parser')
soup_main.body.append(soup_append.a)
print(soup_main)

输出:

<html><head></head><body><a>FooBar</a><a>Meh</a></body></html>

希望它有所帮助。