“美丽”组中的第一个元素

2024-04-20 13:37:49 发布

您现在位置:Python中文网/ 问答频道 /正文

有个有趣的问题。你知道吗

注:已将lxml和bs4升级至最新版本,版本相同。你知道吗

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

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

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的格式是一致的(附在gisthere

对元素0调用entry['title']返回"The Offspring"(正确),但对元素0调用entry.text返回整个文件。你知道吗

我是不是遗漏了一些xml头之类的东西?你知道吗


Tags: 文件the文档版本doctagsxmlall
1条回答
网友
1楼 · 发布于 2024-04-20 13:37:49

使用完整文件,如果您在xml中搜索<div style="float:left;">,您将看到没有导致问题的结束标记。你知道吗

使用错误的行:

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.html.soupparser组合lxml和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

相关问题 更多 >