scrapy xpath 取值
时间: 2023-09-20 13:13:29 浏览: 50
Scrapy可以使用XPath语法来从HTML或XML文档中提取数据。以下是使用XPath在Scrapy中提取值的一些示例:
1. 选择元素:
```
response.xpath('//div') # 选择所有的div元素
response.xpath('//div[@class="example"]') # 选择class属性为example的div元素
```
2. 提取文本:
```
response.xpath('//div/text()').get() # 提取第一个div元素的文本
response.xpath('//div/text()').getall() # 提取所有div元素的文本
```
3. 提取属性:
```
response.xpath('//img/@src').get() # 提取第一个img元素的src属性值
response.xpath('//a/@href').getall() # 提取所有a元素的href属性值
```
4. 使用索引:
```
response.xpath('//div[1]') # 选择第一个div元素
response.xpath('//div[last()]') # 选择最后一个div元素
response.xpath('//div[position()=2]') # 选择第二个div元素
```
5. 使用contains()函数:
```
response.xpath('//div[contains(@class, "example")]') # 选择class属性包含example的div元素
```
6. 使用starts-with()函数:
```
response.xpath('//div[starts-with(@class, "ex")]') # 选择class属性以ex开头的div元素
```
7. 使用normalize-space()函数:
```
response.xpath('normalize-space(//div[@class="example"]/text())') # 提取class属性为example的div元素的文本,并去除首尾空格
```
注意:以上示例中的response代表Scrapy获取的网页响应对象。在Spider中,可以使用response.xpath()方法来执行XPath查询并提取数据。