Python 靓汤

Python 靓汤,python,beautifulsoup,Python,Beautifulsoup,我不明白这为什么不起作用 soup_main = BeautifulSoup('<html><head></head><body><a>FooBar</a></body></html>') soup_append = BeautifulSoup('<html><head></head><body><a>Meh</a></bo

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

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)
soup\u main=beautifulsou('FooBar'))
汤\u append=beautifulsou('Meh')
汤\u主体.append(汤\u 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.
Traceback(最近一次调用last):文件“”,第1行,在
文件“C:\Python34\lib\site packages\bs4\element.py”,第378行,在append中
self.insert(len(self.contents),标记)
文件“C:\Python34\lib\site packages\bs4\element.py”,第312行,插入
raise VALUERROR(“无法在标记中插入None”)
ValueError:无法在标记中插入None。
如果我能理解正在发生的事情,我将非常高兴。

试试这个:

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)
soup\u main=beautifulsou('FooBar','html.parser')
soup\u append=BeautifulSoup('Meh','html.parser')
汤\u主体.append(汤\u append.a)
打印(主汤)
产出:

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

希望有帮助。

是的,我错过了“html.parser”,但问题是我想递归地执行它。因此,如果我尝试再次添加它,它将失败。soup\u main.body.append(soup\u append.a)此操作失败。这是因为当您第一次追加时,
soup\u append.a
变为
None
。在第一次追加后检查此值。这有助于我进行调试。我现在有我想要的了。谢谢。我复制了你的代码,它正在工作(证明:)。你确定你在这里粘贴了相同的代码和HTML吗?