Web Scraping in Python
Thomas Laetsch
Data Scientist, NYU
from scrapy import Selector
html = '''
<html>
<body>
<div class="hello datacamp">
<p>Hello World!</p>
</div>
<p>Enjoy DataCamp!</p>
</body>
</html>
'''
sel = Selector( text = html )
Einen scrapy-Selector aus einem String mit dem HTML-Code erstellt
Der Selector sel hat das gesamte HTML-Dokument ausgewählt
Mit xpath innerhalb eines Selector lassen sich neue Selector für bestimmte HTML-Teile erstellen
Die Rückgabe ist eine SelectorList mit Selector-Objekten
sel.xpath("//p")# liefert die SelectorList: [<Selector xpath='//p' data='<p>Hello World!</p>'>, <Selector xpath='//p' data='<p>Enjoy DataCamp!</p>'>]
extract()>>> sel.xpath("//p")out: [<Selector xpath='//p' data='<p>Hello World!</p>'>, <Selector xpath='//p' data='<p>Enjoy DataCamp!</p>'>]
>>> sel.xpath("//p").extract()out: [ '<p>Hello World!</p>', '<p>Enjoy DataCamp!</p>' ]
extract_first() bekommst du das erste Element der Liste>>> sel.xpath("//p").extract_first()out: '<p>Hello World!</p>'
ps = sel.xpath('//p')second_p = ps[1]
second_p.extract()out: '<p>Enjoy DataCamp!</p>'
Web Scraping in Python