2010-01-18 7 views
5

Ich habe diese XPath-Abfrage bekommt:Wie extrahiere ich Links von einer Webseite mit lxml, XPath und Python?

/html/body//tbody/tr[*]/td[*]/a[@title]/@href 

Es extrahiert alle Links mit dem Titel Attribut - und gibt die href in FireFox's Xpath checker add-on.

Allerdings kann ich nicht scheinen, es mit lxml zu verwenden.

from lxml import etree 
parsedPage = etree.HTML(page) # Create parse tree from valid page. 

# Xpath query 
hyperlinks = parsedPage.xpath("/html/body//tbody/tr[*]/td[*]/a[@title]/@href") 
for x in hyperlinks: 
    print x # Print links in <a> tags, containing the title attribute 

Dies führt zu keinem Ergebnis von lxml (leere Liste).

Wie würde man den href Text (Link) eines Hyperlinks mit dem Attribut Titel mit lxml unter Python greifen?

+0

Hat das zu analysierende Dokument einen Namespace (xmlns)? –

Antwort

9

konnte ich es mit dem folgenden Code funktioniert:

from lxml import html, etree 
from StringIO import StringIO 

html_string = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd"> 

<html lang="en"> 
<head/> 
<body> 
    <table border="1"> 
     <tbody> 
     <tr> 
      <td><a href="http://stackoverflow.com/foobar" title="Foobar">A link</a></td> 
     </tr> 
     <tr> 
      <td><a href="http://stackoverflow.com/baz" title="Baz">Another link</a></td> 
     </tr> 
     </tbody> 
    </table> 
</body> 
</html>''' 

tree = etree.parse(StringIO(html_string)) 
print tree.xpath('/html/body//tbody/tr/td/a[@title]/@href') 

>>> ['http://stackoverflow.com/foobar', 'http://stackoverflow.com/baz'] 
2

Firefox adds additional html tags zu dem HTML-Code, wenn es macht, den XPath machte durch das Firebug-Tool nicht mit dem tatsächlichen html vom Server zurück zurückgegeben (und welche urllib/2 wird zurückkehren).

Das Entfernen des Tags <tbody> führt im Allgemeinen zum Erfolg.

Verwandte Themen