gpt4 book ai didi

python - BeautifulSoup 第一个元素不正确

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:07 24 4
gpt4 key购买 nike

有一个有趣的问题。

注意:将lxml和bs4升级到最新版本,同样的问题。

我正在解析英文维基百科。我用过wikiextractor.py将我的转储分成几个 xml 文档,每个文档包含大约 100 篇文章,分为 <doc>标签。每篇文章中都有 anchor 标记,我试图捕获这些标记并将其存储在关系字段中。

但是,我遇到了一个奇怪的问题:

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 here)

调用entry['title']在元素 0返回"The Offspring" (正确)但打电话 entry.text在元素 0返回整个文件。

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

最佳答案

如果您在 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,您可以使用带有 bs4 的 html.parser,这会更宽容一些:

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

关于python - BeautifulSoup 第一个元素不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36608540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com