我在python中使用BeautifulSoup解析html
我不知道如何在提取文本元素时插入空格
这是代码:
import BeautifulSoup
soup=BeautifulSoup.BeautifulSoup('<html>this<b>is</b>example</html>')
print soup.text
Run Code Online (Sandbox Code Playgroud)
那么输出就是
thisisexample
但我想为此插入一个空格
是例子
我该如何插入空格?
我写了一些代码来解析html,但结果并不是我想要的:
import urllib2
html = urllib2.urlopen('http://dummy').read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for definition in soup.findAll('span', {"class":'d'}):
definition = definition.renderContents()
print "<meaning>", definition
for exampleofuse in soup.find('span',{"class":'x'}):
print "<exampleofuse>", exampleofuse, "<exampleofuse>"
print "<meaning>"
Run Code Online (Sandbox Code Playgroud)
当class属性为"d"或"x"然后获取字符串时,有什么方法吗?
以下html代码是我要解析的:
<span class="d">calculated by adding several amounts together</span>
<span class="x">an average rate</span>
<span class="x">at an average speed of 100 km/h</span>
<span class="d">typical or normal</span>
<span class="x">average intelligence</span>
<span class="x">20 pounds for dinner is average</span>
Run Code Online (Sandbox Code Playgroud)
然后,这是我想要的结果:
<definition>calculated by adding several amounts together
<example_of_use>an average rate</example_of_use>
<example_of_use>at …Run Code Online (Sandbox Code Playgroud)