在 Scrapy 选择器中使用多个 xpath
Using Multiple xpaths in Scrapy Selector
我必须像这样用Scrapy爬取数据:
<div class="data"
data-name="{"id":"566565", "name":"data1"}"
data-property="{"length":"444", "height":"678"}"
>
data1
</div>
<div class="data"
data-name="{"id":"566566", "name":"data2"}"
data-property="{"length":"555", "height":"777"}"
>
data2
</div>
我需要 data-name
和 data-property
属性。我的选择器是:
selections = Selector(response).xpath('//div[@class="data"]/attribute::data-property').extract()
如何在选择中包含 data-name
属性?
下面的 XPath 应该 return data-property
和 data-name
属性:
//div[@class='data']/attribute::*[name()='data-property' or name()='data-name']
XPath 演示:http://www.xpathtester.com/xpath/e720602b62461f3600989be73eb15aec
如果您需要 return 以特定格式为每个父项 div
将两个属性作为一对 div
,则无法使用纯 XPath 1.0 完成此操作。一些 python 是必需的,也许使用列表理解(未测试):
selections = [div.xpath('concat(@data-property, " ", @data-name)').extract() \
for div in Selector(response).xpath('//div[@class="data"]')]
我必须像这样用Scrapy爬取数据:
<div class="data"
data-name="{"id":"566565", "name":"data1"}"
data-property="{"length":"444", "height":"678"}"
>
data1
</div>
<div class="data"
data-name="{"id":"566566", "name":"data2"}"
data-property="{"length":"555", "height":"777"}"
>
data2
</div>
我需要 data-name
和 data-property
属性。我的选择器是:
selections = Selector(response).xpath('//div[@class="data"]/attribute::data-property').extract()
如何在选择中包含 data-name
属性?
下面的 XPath 应该 return data-property
和 data-name
属性:
//div[@class='data']/attribute::*[name()='data-property' or name()='data-name']
XPath 演示:http://www.xpathtester.com/xpath/e720602b62461f3600989be73eb15aec
如果您需要 return 以特定格式为每个父项 div
将两个属性作为一对 div
,则无法使用纯 XPath 1.0 完成此操作。一些 python 是必需的,也许使用列表理解(未测试):
selections = [div.xpath('concat(@data-property, " ", @data-name)').extract() \
for div in Selector(response).xpath('//div[@class="data"]')]