To explain how to use the selectors we’ll use the Scrapy shell (which provides interactive testing) and an example page located in the Scrapy documentation server:
https://docs.scrapy.org/en/latest/_static/selectors-sample1.html

Example website
进入命令行交互模式:
scrapy shell https://docs.scrapy.org/en/latest/_static/selectors-sample1.html

输入
response.selector
输出:request内置的selector选择器

let’s construct an XPath for selecting the text inside the title tag:
response.xpath("//title/text()")
输出选择器与内容.

response.css("title::text").get()

xpath查找images标签
response.xpath('//div[@id="images"]')

response.xpath('//div[@id="images"]').css("img")

css可以用::attr()获取属性:
response.xpath('//div[@id="images"]').css("img::attr(src)").extract()

default:查不到内容返回default里内容

href标签:

找属性名称包含image的所有的超链接可以使用contains选项,第一个参数是属性名,第二个属性是要查找的值
response.xpath('//a[contains(@href,"image")]/@href').extract()

CSS的写法:
response.css('a[href*=image]::attr(href)').extract()

假如我们要选择所有a标签里的img里面的src属性,用上contains:
response.xpath('//a[contains(@href,"image")]/img/@src').extract()

CSS:注意[]之后要有空格
response.css('a[href*=image] img::attr(src)').extract()

提取内容

提取冒号后的内容,就需要正则表达式了,注意,\用来对:进行转义。
response.css('a::text').re('Name\:(.*)')

与extract()方法类似,re也提供了取得列表中第一个元素的方法:re_first()
response.css('a::text').re_first('Name\:(.*)')

进一步地,可以使用strip()方法,去掉返回结果中前后的空格:
response.css('a::text').re_first('Name\:(.*)').strip()

response为我们提供了几个提取方法:
返回的结果都是Selector类型,可以进行嵌套循环。
a) 对css来说:
(b)对xpath来说:
两种选择方法,写法不同,效果类似。
要从selector变为数据,则在后面加上.extract() 或 .extract()_first() 或.extract()[x](x为list中元素的下标)。
如果要提取更具体的信息,可以用正则表达式的方法,在后面加上 .re() 或 .re()_first 进行嵌套选择。