python - 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'
.
解决方案
这不是一个理想的答案,但我最终使用了字符串操作。有些 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
推荐阅读
- julia - 我们如何在 Julia 语言中表示 Python/numpy 函数“zeros_like”
- botframework - 自适应卡片显示在 cortana 频道上不显示,但在团队和模拟器上运行良好
- python - Need to extract all links from script tag HTML Python
- javascript - Sass 中的三和号
- angular - Angular-cli 和 Ckeditor4 自定义构建
- python - 将原始硬盘映像从 S3 存储桶转换为 EC2 映像
- c# - 打开 OpenFileDialog 以更改 PropertyGrid 控件中的属性值?
- arrays - 打字稿参数 - 对象的通用数组和对象键的数组(部分)
- c# - C# Linq 过滤器和求和数据表
- python - 从元素列表中删除元素列表