Python 美化组第一个元素不正确

Python 美化组第一个元素不正确,python,xml,beautifulsoup,Python,Xml,Beautifulsoup,我有一个有趣的问题 注:已将lxml和bs4升级至最新版本,版本相同 我正在解析英文维基百科。我使用了wikiextractor.py将我的转储文件分解成几个xml文档,每个文档包含大约100篇文章,并分成标记。在每一篇文章中都有锚定标记,我正试图捕获并存储在关系字段中 然而,我有一个奇怪的问题: collection = BeautifulSoup(file, 'lxml') entry = collection.find_all('doc')[0].find_all('a') #this r

我有一个有趣的问题

注:已将lxml和bs4升级至最新版本,版本相同

我正在解析英文维基百科。我使用了
wikiextractor.py
将我的转储文件分解成几个xml文档,每个文档包含大约100篇文章,并分成
标记。在每一篇文章中都有锚定标记,我正试图捕获并存储在关系字段中

然而,我有一个奇怪的问题:

collection = BeautifulSoup(file, 'lxml')
entry = collection.find_all('doc')[0].find_all('a')
#this returns ALL anchor tags in the entire xml file
#but...
entry = collection.find_all('doc')[1].find_all('a')
#returns only the anchor tags for that specific entry.
xml的格式是一致的(附在gist中)

在元素
0
上调用
entry['title']
返回
“子代”
(正确),但在元素
0
上调用
entry.text
返回整个文件


我是否缺少一些xml头或其他内容?

使用完整文件,如果在xml中搜索
,您将看到没有导致问题的结束标记

使用错误的行:

In [2]: from bs4 import BeautifulSoup    
In [3]: collection = BeautifulSoup(open("foo.xml").read(),"lxml")   
In [4]: e1 = collection.find('doc').find_all('a')    
In [5]: e2 = collection.find_all('doc')[1].find_all('a')    
In [6]: len(e1)
6411    
In [7]: len(e2)
43    
In [8]: len(collection.find_all("a"))
6411    
In [9]: len(collection.find('doc').text)
819562    
In [10]:len(collection.find_all('doc')[1].text)
3908    
In [11]: len(collection.text)
819562
删除错误行:

In [28]: from bs4 import BeautifulSoup    
In [29]: collection = BeautifulSoup(open("foo.xml").read(),"lxml")    
In [30]: e1 = collection.find('doc').find_all('a')    
In [31]: e2 = collection.find_all('doc')[1].find_all('a')    
In [32]: len(e1)
Out[32]: 260    
In [33]: len(e2)
Out[33]: 43    
In [34]: len(collection.find_all("a"))
Out[34]: 6411   
In [35]: len(collection.find('doc').text
Out[35]: 22882    
In [36]: len(collection.find_all('doc')[1].text)
Out[36]: 3908    
In [37]: len(collection.text)
Out[37]: 819564
对于损坏的html,您可以将html.parser与bs4一起使用,这一点更为宽容:

In [57]: from bs4 import BeautifulSoup

In [58]: collection = BeautifulSoup(open("foo.xml").read(),"html.parser")    
In [59]: e1 = collection.find('doc').find_all('a')    
In [60]: e2 = collection.find_all('doc')[1].find_all('a')    
In [61]: (len(e1))
Out[61]: 260    
In [62]: (len(e2))
Out[62]: 43    
In [63]: (len(collection.find_all("a")))
Out[63]: 6411    
In [64]: (len(collection.find('doc').text))
Out[64]: 22881    
In [65]: (len(collection.find_all('doc')[1].text))
Out[65]: 3910   
In [66]: (len(collection.text))
Out[66]: 819582
或者使用以下方法组合lxml和bs4:


有趣。我只是把文件的一部分贴到要点上。这里是全部内容:你介意再检查一下吗@伊恩,问题实际上是XML的问题。你是在诱导,还是发现了错误?@ian,看看编辑,删除那一行,然后运行你的代码哦,天哪。非常感谢你。在bs4中是否有方法忽略所有样式标记?如果我有成百上千个这样的文件,你会推荐什么?
In [69]: from lxml.html.soupparser import parse    
In [70]: xml = parse(open("foo.xml"))    
In [71]: e3 = xml.xpath("//doc[1]//a")   
In [72]: e4 = xml.xpath("//doc[2]//a")    
In [73]: (len(e3))
Out[73]: 260    
In [74]: (len(e4))
Out[74]: 43    
In [75]: (len(xml.xpath("//a")))
Out[75]: 6411