find_next_sibling - web scraping python examples
No pongas etiquetas html, cabeza y cuerpo automáticamente, beautifulsoup (5)
Otra solución más:
from bs4 import BeautifulSoup
soup = BeautifulSoup(''<p>Hello <a href="http://google.com">Google</a></p><p>Hi!</p>'', ''lxml'')
# content handling example (just for example)
# replace Google with StackOverflow
for a in soup.findAll(''a''):
a[''href''] = ''http://stackoverflow.com/''
a.string = ''StackOverflow''
print ''''.join([unicode(i) for i in soup.html.body.findChildren(recursive=False)])
Al usar beautifulsoup con html5lib, coloca las etiquetas html, head y body automáticamente:
BeautifulSoup(''<h1>FOO</h1>'', ''html5lib'') # => <html><head></head><body><h1>FOO</h1></body></html>
¿Hay alguna opción que pueda configurar, desactivar este comportamiento?
Puedes eliminar html y body especificando soup.body.<tag> :
# python3: first child
print(next(soup.body.children))
# if first child''s tag is rss
print(soup.body.rss)
También puedes usar el desenvolver para quitar el cuerpo, la cabeza y el html
soup.html.body.unwrap()
if soup.html.select(''> head''):
soup.html.head.unwrap()
soup.html.unwrap()
Si carga un archivo xml, bs4.diagnose(data) le indicará que use lxml-xml , que no envolverá su sopa con html+body
>>> BS(''<foo>xxx</foo>'', ''lxml-xml'')
<foo>xxx</foo>
Si quieres que se vea mejor, prueba esto:
BeautifulSoup ([contenido que desea analizar]. Interpretar () )
Su única opción es no usar html5lib para analizar los datos.
Esa es una característica de la biblioteca html5lib , corrige el HTML que falta, como agregar elementos faltantes que faltan.
In [35]: import bs4 as bs
In [36]: bs.BeautifulSoup(''<h1>FOO</h1>'', "html.parser")
Out[36]: <h1>FOO</h1>
Esto analiza el HTML con el analizador HTML incorporado de Python . Citando los documentos:
A diferencia de html5lib, este analizador no intenta crear un documento HTML bien formado al agregar una etiqueta
<body>. A diferencia de lxml, ni siquiera se molesta en agregar una etiqueta<html>.
Alternativamente, puede usar el analizador html5lib y simplemente seleccionar el elemento después de <body> :
In [61]: soup = bs.BeautifulSoup(''<h1>FOO</h1>'', ''html5lib'')
In [62]: soup.body.next
Out[62]: <h1>FOO</h1>