如何用BeautifulSoup连接两个html文件体?

wer*_*ika 6 html python beautifulsoup

我需要将两个html文件的主体连接成一个html文件,其间有一些任意html作为分隔符.我有代码曾经为此工作,但当我从Xubuntu 11.10(或11.04?)升级到12.10时停止工作,可能是由于BeautifulSoup更新(我目前正在使用3.2.1;我不知道我之前有什么版本)或vim更新(我使用vim从纯文本中自动生成html文件).这是代码的精简版:

from BeautifulSoup import BeautifulSoup
soup_original_1 = BeautifulSoup(''.join(open('test1.html')))
soup_original_2 = BeautifulSoup(''.join(open('test2.html')))
contents_1 = soup_original_1.body.renderContents()
contents_2 = soup_original_2.body.renderContents()
contents_both = contents_1 + "\n<b>SEPARATOR\n</b>" + contents_2
soup_new = BeautifulSoup(''.join(open('test1.html')))
while len(soup_new.body.contents):
    soup_new.body.contents[0].extract()
soup_new.body.insert(0, contents_both)                       
Run Code Online (Sandbox Code Playgroud)

用于测试用例的两个输入文件的主体非常简单:contents_1\n<pre>\nFile 1\n</pre>\n'contents_2'\n<pre>\nFile 2\n</pre>\n'.

我希望soup_new.body.renderContents()将这两者与这两者之间的分隔符串联起来,而不是将所有的<变为&lt;等等 - 所需的结果是'\n<pre>\nFile 1\n</pre>\n\n<b>SEPARATOR\n</b>\n<pre>\nFile 2\n</pre>\n',这是我在操作系统更新之前得到的结果; 目前的结果是'\n&lt;pre&gt;\nFile 1\n&lt;/pre&gt;\n\n&lt;b&gt;SEPARATOR\n&lt;/b&gt;\n&lt;pre&gt;\nFile 2\n&lt;/pre&gt;\n',这是非常没用的.

将html作为字符串插入汤对象的体内时,如何使BeautifulSoup停止<转入&lt;等?或者我应该以完全不同的方式做这件事?(这是我对BeautifulSoup和大多数其他html解析的唯一体验,所以我猜这可能就是这种情况.)

html文件是用vim的纯文本文件自动生成的(我使用的真实案例显然更复杂,并且涉及自定义语法高亮,这就是为什么我这样做的原因).完整的test1.html文件如下所示,test2.html除内容和标题外完全相同.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>~/programs/lab_notebook_and_printing/concatenate-html_problem_2013/test1.txt.html</title>
<meta name="Generator" content="Vim/7.3" />
<meta name="plugin-version" content="vim7.3_v10" />
<meta name="syntax" content="none" />
<meta name="settings" content="ignore_folding,use_css,pre_wrap,expand_tabs,ignore_conceal" />
<style type="text/css">
pre { white-space: pre-wrap; font-family: monospace; color: #000000; background-color: #ffffff; white-space: pre-wrap; word-wrap: break-word }
body { font-family: monospace; color: #000000; background-color: #ffffff; font-size: 0.875em }
</style>
</head>
<body>
<pre>
File 1
</pre>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

aba*_*ert 10

试图将HTML作为文本阅读只是为了将其插入到HTML中并在两个方向上进行编码和解码,这使得很多额外的工作变得非常困难.

最简单的事情就是不这样做.你想在test1的主体中的所有内容之后在test2的主体中插入所有内容,对吧?所以就这样做:

for element in soup_original_2.body:
    soup_original_1.body.append(element)
Run Code Online (Sandbox Code Playgroud)

要首先附加分隔符,只需对分隔符执行相同的操作:

b = soup.new_tag('b')
b.append('SEPARATOR')
soup.original_1.body.append(b)
for element in soup_original_2.body:
    soup_original_1.body.append(element)
Run Code Online (Sandbox Code Playgroud)

而已.

请参阅文档部分修改树以获取涵盖所有这些内容的教程.

  • 我无法将元素从一个'汤'添加到另一个'汤'.附加`copy.deepcopy(element)`帮助. (3认同)