需要帮助尝试将len(item)添加为索引。

问题描述 投票:-2回答:3

我正在试图抓取一些数据,我认为我找到了解决方案,但我正在努力为它编写代码。

# 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总是在变化。我假设我需要为此编写一个新函数。任何帮助将不胜感激。

python web-scraping scrapy
3个回答
-1
投票

在那里使用变量而不是常数:

因此,第一步只需提取描述的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_:]

0
投票

代码

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]

总的来说,你在这里要问的不是很清楚。你能改一下你的问题吗?


-1
投票
# 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:]

Here is an example to make it clear :

>>> 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:]表示列表的开头或完整列表。

© www.soinside.com 2019 - 2024. All rights reserved.