2011-03-04 8 views
0
<a href="/watch?gl=US&amp;client=mv-google&amp;hl=en&amp;v=0C_yXOhJxWg">Miss Black OCU 2011</a> 

Mon programme lit un fichier html, et en haut est le morceau de ce fichier. Je veux saisir Miss Black OCU 2011 en utilisant BeautifulSoup en python. Aucune suggestion?Python: analyse de code HTML avec BeautifulSoup

Répondre

0

Je suggère de regarder les attributs de la classe Tag et NavigableString

text = """<a href="/watch?gl=US&amp;client=mv-google&amp;hl=en&amp;v=0C_yXOhJxWg">Miss Black OCU 2011</a>""" 
soup = BeautifulSoup(text) 
print soup.find('a').text 
0

Si l'attribut href suivent un modèle littéral comme href = « ... regarder ... » Vous pouvez facilement résoudre le problème en utilisant re: expression régulière.

import re 
from bs4 import BeautifulSoup 
response = """<a href="/watch?gl=US&amp;client=mv-google&amp;hl=en&amp;v=0C_yXOhJxWg">Miss Black OCU 2011</a>""" 
# the response should might be the urlreponse object if you search through a whole html page 
soup = BeautifulSoup(response) 
print soup.find("a", {"href":re.compile(".*watch.*")}).text 

La sortie est comme ceci:

Miss Black OCU 2011 

Le tout est de trouver le modèle d'expression régulière. Plus d'infos sur re, cliquez ici http://docs.python.org/2/library/re.html:

Questions connexes