我正在使用 BeautifulSoup 创建和编写 html 文件。我能够为 MWE 创建一个简单的 html,如下所示。然而,所有find函数都不返回任何内容,因此无法执行进一步的操作(插入、追加)。
- 发生了什么事?
- 如何单独为其中一个 div 设置样式? (例如,div2 和 div3 应该有 display:none ,稍后我计划通过脚本启用)
MWE:
head_soup = BeautifulSoup(open(nbheader_template),"html.parser")
head_soup.contents[0]
base_template = "<!DOCTYPE html><html></html>"
main_soup = BeautifulSoup(base_template,"html.parser")
main_soup.html.append(head_soup) # add nbconver header
# INSERT THE BODY AS IT IS
# bodies = [body.replace('<body>','').replace('</body>','') for body in bodies] # no need of body tags
bodies = ['<div>Test div' + str(i+1) + '</div>' for i in range(3)] # for MWE
body_tag = main_soup.new_tag('body')
for each_body in bodies:
body_tag.append(BeautifulSoup(each_body,'html.parser'))
main_soup.html.insert(1,body_tag)
with open(output_filename, "w") as file:
file.write(str(main_soup))
print(main_soup.find_all('head'))
print(main_soup.html.find_all('head'))
print(main_soup.find_all('body'))
print(main_soup.html.find_all('body'))
print(main_soup.find_all('div'))
print(main_soup.html.find_all('div'))
上下文:我正在尝试合并多个 jupyter 笔记本 html 文件。在此更新之后,我需要将样式添加到与每个 html(每个笔记本)文件相对应的各个 div。
Here是nbviewer头
最佳答案
看起来 BeautifulSoup 没有正确地将新的可导航字符串添加为可导航字符串,而是添加为字符串。这使得它们的查找函数不起作用,但是如果您使用 main_soup.prettify() 并将其反馈到 beautiful soup 中,您就可以按预期导航输出。
main_soup
<!DOCTYPE html>
<html><body><div>Test div1</div><div>Test div2</div>
<div>Test div3</div></body></html>
>>> new_soup = BeautifulSoup(main_soup.prettify())
>>> new_soup.body
<body>
<div>
Test div1
</div><div>
Test div2
</div><div>
Test div3
</div>
</body>
>>> new_soup.html.find_all('div')
[<div>
Test div1
</div>, <div>
Test div2
</div>, <div>
Test div3
</div>]
要将样式设置为其中一个 div,您可以导航到它,然后添加您要添加的样式的类。除非您只想在一个地方使用该样式,否则为每个单独的 div 设置不同的样式会变得很繁重。我建议使用带有类的 css 来定义您想要的 div 的样式。
关于python - BeautifulSoup 成功写入 html 但 find_all 什么也没返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53614327/