.class .color 选择class=”color”的所有元素 #id #info 选择id=”info”的所有元素 * * 选择所有元素 element p 选择所有的p元素 element,element div,p 选择所有div元素和所有p元素 element element div p 选择div标签内部的所有p元素 [attribute] [target] 选择带有targe属性的所有元素 [arrtibute=value] [target=_blank] 选择target=”_blank”的所有元素
In [11]: response.xpath('//a/@href').extract() Out[11]: ['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']
In [14]: response.xpath('//a/text()').extract() Out[14]: ['Name: My image 1 ', 'Name: My image 2 ', 'Name: My image 3 ', 'Name: My image 4 ', 'Name: My image 5 ']
In [16]: response.css('a::attr(href)').extract() Out[16]: ['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']
In [17]: response.css('a::text').extract() Out[17]: ['Name: My image 1 ', 'Name: My image 2 ', 'Name: My image 3 ', 'Name: My image 4 ', 'Name: My image 5 ']
高级用法
查找属性名称包含img的所有的超链接,通过contains实现
1 2 3 4 5
In [18]: response.xpath('//a[contains(@href,"image")]/@href').extract() Out[18]: ['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']
In [19]: response.css('a[href*=image]::attr(href)').extract() Out[19]: ['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']
查找img的src属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
In [20]: response.xpath('//a[contains(@href,"image")]/img/@src').extract() Out[20]: ['image1_thumb.jpg', 'image2_thumb.jpg', 'image3_thumb.jpg', 'image4_thumb.jpg', 'image5_thumb.jpg']
In [22]: response.css('a[href*=image] img::attr(src)').extract() Out[22]: ['image1_thumb.jpg', 'image2_thumb.jpg', 'image3_thumb.jpg', 'image4_thumb.jpg', 'image5_thumb.jpg']
提取a标签的文本中name后面的内容,这里提供了正则的方法re和re_first
1 2 3 4 5 6 7 8 9 10 11
In [23]: response.css('a::text').re('Name\:(.*)') Out[23]: [' My image 1 ', ' My image 2 ', ' My image 3 ', ' My image 4 ', ' My image 5 ']
In [24]: response.css('a::text').re_first('Name\:(.*)') Out[24]: ' My image 1 '