Giới thiệu về scrapy Selector

Web Scraping với Python

Thomas Laetsch

Data Scientist, NYU

Thiết lập Selector

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 )
  • Tạo đối tượng scrapy Selector từ chuỗi chứa mã html

  • Selector sel đã chọn toàn bộ tài liệu html

Web Scraping với Python

Chọn các Selector

  • Dùng xpath trong Selector để tạo Selector mới cho các phần cụ thể của mã html

  • Kết quả là SelectorList gồm các đối tượng Selector

sel.xpath("//p")

# xuất ra SelectorList: [<Selector xpath='//p' data='<p>Hello World!</p>'>, <Selector xpath='//p' data='<p>Enjoy DataCamp!</p>'>]
Web Scraping với Python

Trích xuất dữ liệu từ SelectorList

  • Dùng phương thức 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>' ]
  • Dùng extract_first() để lấy phần tử đầu tiên của danh sách
>>> sel.xpath("//p").extract_first()

out: '<p>Hello World!</p>'
Web Scraping với Python

Trích xuất dữ liệu từ Selector

ps = sel.xpath('//p')

second_p = ps[1]
second_p.extract()

out: '<p>Enjoy DataCamp!</p>'
Web Scraping với Python

Chọn khóa học này!

Web Scraping với Python

Preparing Video For Download...