【问题标题】:Need help on trying to add the len(item) as an index.在尝试将 len(item) 添加为索引时需要帮助。
【发布时间】:2017-12-25 07:11:22
【问题描述】:

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

# This returns a list that changes depending on the page     
description = response.xpath('.//*[@class="txtGrey size14-description"]/text()').extract()

我需要获取准确的 len(description) 并将该长度添加为描述的索引(不确定我是否正确使用了单词 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 是什么,我都会用它来索引描述。我遇到了一个障碍,当我将抓取的数据输出为 csv 时,“描述”单元格始终为空。虽然当我使用 [-1:] 作为索引时,那些在描述中只有 1 个列表的会出现,其余的不会出现。我希望通过使用确切的 len,我能够使所有描述正常工作。
  • 仍然没有例子不清楚你真正想要达到的目标。

标签: python web-scraping scrapy


【解决方案1】:

代码

my_list[-len(my_list):]

将始终返回原始列表(实际上是副本),因为

my_list[-x:]

表示“获取my_list 的最后一个x 元素”,并且您将x 设置为列表中的元素数,因此它会获取所有元素。

例如:

In [1]: my_list = [1, 2, 3, 4]

In [2]: my_list[-len(my_list):]
Out[2]: [1, 2, 3, 4]

总的来说,你在这里问什么不是很清楚。你能改写你的问题吗?

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我明白我做错了什么。我试图通过 '[' + len_ + ':]' 连接 len_ 。如果您有时间,您能否向我解释为什么我无法以这种方式连接它?不管怎样,谢谢你的帮助=)
    • @DanielAhn 如果我的解决方案对您有帮助,您可以accept the answer.
    • @DanielAhn 你确实意识到,当你这样做时,你得到的结果与简单地使用 extract() 没有任何额外的代码一样吗?正如其他两个答案告诉你的那样, x[-len(x):] == x
    • @Gnudiff 我忘了条件,我已经更新了。
    • 是的,我现在确实意识到了,哈哈。尝试解决方案后,导出的 csv 文件仍然有空白单元格。我将不得不做更多的调试,为什么它不能正确输出。我现在假设这是因为我将它作为 csv 输出,因为当我作为 json 输出时,描述信息在 csv 上显示为空白单元格。
    【解决方案3】:
    # 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:] 表示从开头到列表末尾或再次完整列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 2014-01-19
      • 2015-09-25
      • 2013-10-17
      • 2011-06-07
      相关资源
      最近更新 更多