Estoy migrando algunos analizadores de BeautifulSoup3 a BeautifulSoup4 y pensé que sería una buena idea hacer un perfil de lo rápido que sería, teniendo en cuenta que lxml es súper rápido y es el analizador que estoy usando con BS4, aquí son los resultados de perfil:Beautifulsoup4 con lxml contra Beautifulsoup3
Para 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 <string>:2(<module>)
18 0.000 0.000 0.000 0.000 <string>:8(__new__)
1 0.000 0.000 0.072 0.072 <string>: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)
...
Para BS4 usando lxml:
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 <string>:2(<module>)
18 0.000 0.000 0.000 0.000 <string>:8(__new__)
1 0.000 0.000 0.158 0.158 <string>:9(parser)
1 0.000 0.000 0.008 0.008 HTMLParser.py:1(<module>)
1 0.000 0.000 0.000 0.000 HTMLParser.py:54(HTMLParseError)
...
qué BS4
está llamando 4 tim es más funciones? ¿Por qué está usando el HTMLParser
si configuro para usar lxml
?
Las cosas más notables que ha cambiado de BS3 a BS4 eran esto:
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]]
todo lo demás es sólo un cambio de nombre (como findParent -> find_parent)
EDIT:
mi entorno:
python 2.7.3
beautifulsoup4==4.1.0
lxml==2.3.4
EDITAR 2:
He aquí una pequeña muestra de código para probarlo:
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()
No podemos reproducir sus resultados si no nos proporciona una URL de muestra para trabajar con la que expone este problema. (Además, ¿ha determinado si lxml.html exhibe este problema, o solo BS4?) –
solo BS4, no lo ha intentado solo con lxml. Permítanme crear un ejemplo fácil muy rápido para que puedan reproducirlo – Hassek
bien, simplemente agregué un pequeño ejemplo para que todos puedan probarlo – Hassek