首页 > 解决方案 > Scrapy 使用 getall() 获取 xPath 属性

问题描述

我正在使用 Scrapy 来构建一个 ID 列表(稍后将在 URL 中使用它来抓取更多数据):

def parse(self, response):
    for a in response.xpath('//a[@class="imageLink"]').getall():  
        print(a)
        item = NgaItem1()
        item["itemId"] = a.attrib["assetid"]
        yield item

我相信我正确选择了 DOM 元素,为print(a)我感兴趣的每个元素返回以下内容:

<a class="imageLink" id="assetLink_A_148957" assetid="148957" assettype="A" rel=""><img style="max-width:128px;max-height:128px;" class="mainThumbImage imageDraggable" alt="" title="George Catlin - The White Cloud, Head Chief of the Iowas - 1844/1845 - Painting" rel="" offset="" onmousedown="
                                                        noclear = 1; noclear=0;
                                                " id="grid-item_A_148957" assetid="148957" src="https://images.nga.gov//assets/thumbnails/497/7/5a7e73ae456e734fe2eaf4a0a71f0e3d.jpg"></a>

我所需要的只是资产 ID 148957。我得到的错误是'str' object has no attribute 'attrib'.

标签: pythonscrapy

解决方案


这不是一个理想的答案,但我最终使用了字符串操作。有些 ID 是 5 位数,有些是 6,所以我后来在 Excel 中做了一些清理工作。

def parse(self, response):
    for a in response.xpath('//a[@class="imageLink"]').getall():  
        start = a.find('assetid')
        item = NgaItem1()
        item["itemId"] = a[start+9:start+15]
        print(item["itemId"])
        yield item

推荐阅读