[英]Scrapy get xPath attribute with getall()
我正在使用 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>
我只需要 assetid 148957。我得到的错误是'str' object has no attribute 'attrib'
。
这不是一个理想的答案,但我最终使用了字符串操作。 有些 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.