Selecția atributelor și textului

Web Scraping în Python

Thomas Laetsch

Data Scientist, NYU

Trebuie să fiți curajoși cu două puncte

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

Extragerea textului

<p id="p-example">
  Hello world! 
  Try <a href="http://www.datacamp.com">DataCamp</a> today!
</p>
  • În XPath se folosește 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 în Python

Extragerea textului

<p id="p-example">
  Hello world! 
  Try <a href="http://www.datacamp.com">DataCamp</a> today!
</p>
  • Pentru CSS Locator, se folosește ::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 în Python

Utilizarea corectă a două puncte

Web Scraping în Python

Preparing Video For Download...