我正在试图抓取一些数据,我认为我找到了解决方案,但我正在努力为它编写代码。
# This returns a list that changes depending on the page
description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract()
我需要得到精确的len(描述)并将该长度添加为描述的索引(不确定我是否正确使用单词index)
所以举个例子
description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract()
len(description)
如果描述的长度是4
代码需要说
description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract()[-4:]
注意:我需要' - '和':'。
我将翻阅几页,因此len总是在变化。我假设我需要为此编写一个新函数。任何帮助将不胜感激。
在那里使用变量而不是常数:
因此,第一步只需提取描述的len()并将len保存到变量:
len_= int(response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract())
然后通过if
条件检查:
if len(len_)==4:
如果满足以上条件,则执行以下代码:
第二步现在使用该变量作为index_no进行切片:
description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract()[-len_:]
代码
my_list[-len(my_list):]
将永远返回原始列表(实际上是一个副本),因为
my_list[-x:]
意思是“获取x
的最后一个my_list
元素”,并且你将x
设置为列表中元素的数量,因此它可以获得所有这些元素。
例如:
In [1]: my_list = [1, 2, 3, 4]
In [2]: my_list[-len(my_list):]
Out[2]: [1, 2, 3, 4]
总的来说,你在这里要问的不是很清楚。你能改一下你的问题吗?
# This returns a list that changes depending on the page
description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract()
找到长度
len(description)
假设长度为4.所以做你正在做的事情将再次返回相同的列表
description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract()[-4:]
>>> a=[1,2,3,4,5,6,7,8,9]
>>> print(a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> len(a)
9
>>> a=a[-(len(a)):]
>>> print(a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(a[-9])
1
这是因为[-9]指向列表的开头,因此[-9:]表示列表的开头或完整列表。