Sélection d’attributs et de texte

Web Scraping en Python

Thomas Laetsch

Data Scientist, NYU

Il faut oser utiliser les deux-points

  • Avec XPath : <xpath-to-element>/@attr-name
xpath = '//div[@id="uid"]/a/@href'
  • Avec un sélecteur CSS : <css-to-element>::attr(attr-name)
css_locator = 'div#uid > a::attr(href)'
Web Scraping en Python

Extraction de texte

<p id="p-example">
  Hello world! 
  Try <a href="http://www.datacamp.com">DataCamp</a> today!
</p>
  • En XPath, utilisez 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 en Python

Extraction de texte

<p id="p-example">
  Hello world! 
  Try <a href="http://www.datacamp.com">DataCamp</a> today!
</p>
  • Pour un sélecteur CSS, utilisez ::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 en Python

Portée des deux-points

Web Scraping en Python

Preparing Video For Download...