2011-10-11 17 views

risposta

12

Prima impostare un documento di prova e di aprire il parser con BeautifulSoup:

>>> from BeautifulSoup import BeautifulSoup 
>>> doc = '<html><body><div><a href="something">yep</a></div><div><a href="http://www.nhl.com/ice/boxscore.htm?id=3">somelink</a></div><a href="http://www.nhl.com/ice/boxscore.htm?id=7">another</a></body></html>' 
>>> soup = BeautifulSoup(doc) 
>>> print soup.prettify() 
<html> 
<body> 
    <div> 
    <a href="something"> 
    yep 
    </a> 
    </div> 
    <div> 
    <a href="http://www.nhl.com/ice/boxscore.htm?id=3"> 
    somelink 
    </a> 
    </div> 
    <a href="http://www.nhl.com/ice/boxscore.htm?id=7"> 
    another 
    </a> 
</body> 
</html> 

Avanti, siamo in grado di cercare tutti i <a> tag con un attributo href inizia con http://www.nhl.com/ice/boxscore.htm?id=. È possibile utilizzare un'espressione regolare per esso:

>>> import re 
>>> soup.findAll('a', href=re.compile('^http://www.nhl.com/ice/boxscore.htm\?id=')) 
[<a href="http://www.nhl.com/ice/boxscore.htm?id=3">somelink</a>, <a href="http://www.nhl.com/ice/boxscore.htm?id=7">another</a>] 
+0

Wow, grazie. Immagino che la documentazione di beautifulsoup presupponga una fluenza nella regex. Grazie per avermi mostrato che –

+1

@JenScott Se questo ha risposto alla tua domanda, dovresti accettarlo. – serk

+0

Buono ma cosa succede se il nome dell'attributo è chiamato "classe"? – Wajih

2

Potrebbe non essere necessario BeautifulSoup poiché la ricerca è specifico

>>> import re 
>>> links = re.findall("http:\/\/www\.nhl\.com\/ice\/boxscore\.htm\?id=.+", str(doc)) 
Problemi correlati