CSS 定位器

Python Web 爬取

Thomas Laetsch

Data Scientist, NYU

罗塞塔 CSS 石

  • / 替换为 >(首字符除外)
    • XPath: /html/body/div
    • CSS 定位器: html > body > div
  • // 替换为空格(首字符除外)
    • XPath: //div/span//p
    • CSS 定位器: div > span p
  • [N] 替换为 :nth-of-type(N)
    • XPath: //div/p[2]
    • CSS 定位器: div > p:nth-of-type(2)
Python Web 爬取

罗塞塔 CSS 石

XPATH

xpath = '/html/body//div/p[2]'

CSS

css = 'html > body div > p:nth-of-type(2)'
Python Web 爬取

CSS 中的属性

  • 按类选择,用点号 .
    • 例如:p.class-1 选择属于 class-1 的所有段落元素
  • 按 id 选择,用井号 #
    • 例如:div#uid 选择 id 等于 uiddiv 元素
Python Web 爬取

CSS 中的属性

选择类为 class1 内的段落元素:

css_locator = 'div#uid > p.class1'

选择所有类属性属于 class1 的元素:

css_locator = '.class1'
Python Web 爬取

类状态

css = '.class1'

按类选择-XPath-仅类.png

Python Web 爬取

类状态

xpath = '//*[@class="class1"]'

按类选择-XPath-等于.png

Python Web 爬取

类状态

xpath = '//*[contains(@class,"class1")]'

按类选择-XPath-包含.png

Python Web 爬取

使用 CSS 的选择器

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 )
>>> sel.css("div > p")
out: [<Selector xpath='...' data='<p>Hello World!</p>'>] 

>>> sel.css("div > p").extract()
out: [ '<p>Hello World!</p>' ]
Python Web 爬取

C(SS) You Soon!

Python Web 爬取

Preparing Video For Download...