¿Cuál es la mejor manera de manejar un enlace incorrecto dado a BeautifulSoup?
-
19-08-2019 - |
Pregunta
Estoy trabajando en algo que extrae las URL de delicious y luego las usa para descubrir los feeds asociados.
Sin embargo, algunos de los marcadores de delicious no son enlaces html y provocan que BS vomite. Básicamente, quiero tirar un enlace si BS lo recupera y no parece html.
En este momento, esto es lo que estoy obteniendo.
trillian:Documents jauderho$ ./d2o.py "green data center"
processing http://www.greenm3.com/
processing http://www.eweek.com/c/a/Green-IT/How-to-Create-an-EnergyEfficient-Green-Data-Center/?kc=rss
Traceback (most recent call last):
File "./d2o.py", line 53, in <module>
get_feed_links(d_links)
File "./d2o.py", line 43, in get_feed_links
soup = BeautifulSoup(html)
File "/Library/Python/2.5/site-packages/BeautifulSoup.py", line 1499, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "/Library/Python/2.5/site-packages/BeautifulSoup.py", line 1230, in __init__
self._feed(isHTML=isHTML)
File "/Library/Python/2.5/site-packages/BeautifulSoup.py", line 1263, in _feed
self.builder.feed(markup)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/HTMLParser.py", line 108, in feed
self.goahead(0)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/HTMLParser.py", line 150, in goahead
k = self.parse_endtag(i)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/HTMLParser.py", line 314, in parse_endtag
self.error("bad end tag: %r" % (rawdata[i:j],))
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: bad end tag: u'</b />', at line 739, column 1
Update:
La respuesta de Jehiah hace el truco. Como referencia, aquí hay un código para obtener el tipo de contenido:
def check_for_html(link):
out = urllib.urlopen(link)
return out.info().getheader('Content-Type')
Solución
Simplemente envuelvo mi procesamiento BeautifulSoup y busco la HTMLParser.HTMLParseError
excepción
import HTMLParser,BeautifulSoup
try:
soup = BeautifulSoup.BeautifulSoup(raw_html)
for a in soup.findAll('a'):
href = a.['href']
....
except HTMLParser.HTMLParseError:
print "failed to parse",url
pero más allá de eso, puede verificar el tipo de contenido de las respuestas cuando rastrea una página y asegurarse de que sea algo así como text / html
o application / xml + xhtml o algo así incluso antes de intentar analizarlo. Eso debería evitar la mayoría de los errores.