Selezione di attributi e testo

Web Scraping in Python

Thomas Laetsch

Data Scientist, NYU

Serve coraggio per usare i due punti

  • Con XPath: <xpath-to-element>/@attr-name
xpath = '//div[@id="uid"]/a/@href'
  • Con selettore CSS: <css-to-element>::attr(attr-name)
css_locator = 'div#uid > a::attr(href)'
Web Scraping in Python

Estrazione del testo

<p id="p-example">
  Hello world! 
  Try <a href="http://www.datacamp.com">DataCamp</a> today!
</p>
  • In XPath usa text()
sel.xpath('//p[@id="p-example"]/text()').extract()

# result: ['\n Hello world!\n Try ', ' today!\n']
sel.xpath('//p[@id="p-example"]//text()').extract()

# result: ['\n Hello world!\n Try ', 'DataCamp', ' today!\n']
Web Scraping in Python

Estrazione del testo

<p id="p-example">
  Hello world! 
  Try <a href="http://www.datacamp.com">DataCamp</a> today!
</p>
  • Con selettore CSS, usa ::text
sel.css('p#p-example::text').extract()

# result: ['\n Hello world!\n Try ', ' today!\n']
sel.css('p#p-example ::text').extract()

# result: ['\n Hello world!\n Try ', 'DataCamp', ' today!\n']
Web Scraping in Python

Limitare l'ambito dei due punti

Web Scraping in Python

Preparing Video For Download...