Python 使用Beauty Soup解析Html文件时出现意外输出

Python 使用Beauty Soup解析Html文件时出现意外输出,python,html,beautifulsoup,Python,Html,Beautifulsoup,我有一个基本Html文件,其中包含标签内的文本,如下所示: <head> <title></title> </head> <body> <div>{#One#}</div> <span>{#Two#}</span> <b>{#Three#}</b> <i>four</i> <td>{#five#}</td> <s

我有一个基本Html文件,其中包含标签内的文本,如下所示:

<head>
<title></title>
</head>
<body>
<div>{#One#}</div>
<span>{#Two#}</span>
<b>{#Three#}</b>
<i>four</i>
<td>{#five#}</td>
<sup>{#six#}</sup>
<sub>{#seven#}</sub>
<i>eight</i>
</body>
但是,当我运行程序时,我得到一个奇怪的输出:如下所示:

1  
1
1
1
1
1<i>four</i>
1
1
1
1<i>eight</i>
1
1.
1.
1.
1.
1四
1.
1.
1.
1光
而不是:

 4<i>four</i>
 8<i>eight</i>
4four
八八
我在这里做错了什么,这似乎是一个愚蠢的错误。

使用
find('body')
返回整个
body
标记,其中所有内容都作为单个元素。因此,迭代
bdy
并不能给出您的想法

from bs4 import BeautifulSoup
import re
import urllib2

url = "index.html"
page = open(url)
soup = BeautifulSoup(page.read(), "html.parser")
soup.prettify()
bdy = soup.find('body')
for num, lines in enumerate(bdy):
    for line in lines:
        if line !='\n' and '{' not in line:
            print num, lines
您需要使用
bdy.find_all(True)
,它将返回
正文
中的所有标记。然后,将
if
语句更改为
if'{'不在标记中。text:

soup = BeautifulSoup(html, 'lxml')
bdy = soup.find('body')
for i, tag in enumerate(bdy.find_all(True), 1):
    if '{' not in tag.text:
        print(i, tag)
输出:

4 <i>four</i>
8 <i>eight</i>
4四
八八

print num,lines
br在这里做什么?
是一个打字错误,num指定它所在的行数,行指定文本。什么是
word
?你为什么使用regex而不是更好的可用的beautifulsou函数?
4 <i>four</i>
8 <i>eight</i>