sách gpt4 ăn đã đi

python - Beautifulsoup với lxml so với Beautifulsoup 3

In lại 作者:太空狗 更新时间:2023-10-30 01:35:00 26 4
mua khóa gpt4 giày nike

我正在将一些解析器从 BeautifulSoup3 迁移到 BeautifulSoup4,我认为考虑到 lxml 非常快并且它是我在 BS4 中使用的解析器,分析它会变得多快是个好主意,这里是分析结果:

对于 BS3:

43208 function calls (42654 primitive calls) in 0.103 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :2()
18 0.000 0.000 0.000 0.000 :8(__new__)
1 0.000 0.000 0.072 0.072 :9(parser)
32 0.000 0.000 0.000 0.000 BeautifulSoup.py:1012(__init__)
1 0.000 0.000 0.000 0.000 BeautifulSoup.py:1018(buildTagMap)
...

对于使用 lxml 的 BS4:

164440 function calls (163947 primitive calls) in 0.244 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)
1 0.040 0.040 0.069 0.069 :2()
18 0.000 0.000 0.000 0.000 :8(__new__)
1 0.000 0.000 0.158 0.158 :9(parser)
1 0.000 0.000 0.008 0.008 HTMLParser.py:1()
1 0.000 0.000 0.000 0.000 HTMLParser.py:54(HTMLParseError)
...

Tại sao BS4 调用了 4 倍以上的函数?如果我将它设置为使用 lxml,为什么还要使用 HTMLParser?

我从 BS3 到 BS4 改变的最明显的事情是:

 BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) --->
BeautifulSoup(html, 'lxml')

[x.getText('**SEP**') for x in i.findChildren('font')[:2]] --->
[x.getText('**SEP**', strip=True) for x in i.findChildren('font')[:2]]

其他一切只是一些名称更改(如 findParent --> find_parent)

biên tập:

我的环境:

python 2.7.3
beautifulsoup4==4.1.0
lxml==2.3.4

Chỉnh sửa 2:

这里是一个小代码示例来尝试一下:

from cProfile import Profile

from BeautifulSoup import BeautifulSoup
from bs4 import BeautifulSoup as BS4
import urllib2


def parse(html):

soup = BS4(html, 'lxml')
hl = soup.find_all('span', {'class': 'mw-headline'})
return [x.get_text(strip=True) for x in hl]


def parse3(html):

soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)
hl = soup.findAll('span', {'class': 'mw-headline'})
return [x.getText() for x in hl]


if __name__ == "__main__":
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
html = ''.join(opener.open('http://en.wikipedia.org/wiki/Price').readlines())

profiler = Profile()
print profiler.runcall(parse, html)
profiler.print_stats()

profiler2 = Profile()
print profiler2.runcall(parse3, html)
profiler2.print_stats()

câu trả lời hay nhất

我认为主要问题是 Beautiful Soup 4 中的错误。我已经 filed it并将在下一个版本中发布修复程序。感谢您找到这个。

也就是说,鉴于您使用的是 lxml,我根本不知道为什么您的个人资料会提到 HTMLParser 类。

关于python - Beautifulsoup 与 lxml vs Beautifulsoup 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11297749/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress