【问题标题】:List indices must be integers, not tuple列表索引必须是整数,而不是元组
【发布时间】:2015-07-11 05:56:46
【问题描述】:

我搜索了这个问题并尝试使用上述解决方案,但似乎都没有工作。

我当前的代码是:

 for item in g_data:
     print item.contents[1].find_all("a", {"class": "a-link-normal"})[[1], [2], [3]]['href'] 

这导致TypeError: indices must be integers, not tuple

我该如何解决这个问题?我知道这是一个简单的问题,但我尝试的解决方案导致它出现并说“not list”、“not str”或“not tuple”。

【问题讨论】:

  • 尝试将 [ [1], [2], [3] ] 分成项目....find_all(....)[1] 然后 [2] 然后 [3]跨度>
  • g_data 是什么类型?
  • @RafaelCardoso 你的意思是像这样打印 item.contents[1].find_all("a", {"class": "a-link-normal"})[[1][2][ 3]]['href'] 这导致列表索引超出范围
  • 一般来说,当这种情况发生时,尝试将它分布在多行上,这样你就可以看到确切的 TypeError 来自哪里。
  • 如果你试图从列表中获取第二、第三和第四项,正确的语法不是my_list[[1],[2],[3]],而是my_list[1:4]。如果您尝试从字典列表中的每个项目中获取 href 值,则正确的语法不是 my_list_of_dicts["href"],而是 [d["href"] for d in my_list_of_dicts]

标签: python html integer web-scraping


【解决方案1】:

所以我通过绕过选择问题完全解决了手头的问题。

这就是我所做的:

对于 g_data 中的项目: print item.contents[1].find_all("a", {"class":"a-link-normal s-access-detail-page a-text-normal"})[0]["href"]

它的作用是首先搜索页面上的主要内容(任何 url 都可以在 G_data 中)。接下来它将选择[1],即焦点内容、产品、图像、链接等。它摆脱了所有其他的东西。然后是括号内的部分,它的作用是选择这段内容

大猩猩胶带 11m

现在它不只选择那个,而是选择页面上的所有产品。之后有 [0] 这是第一个产品的选择,所以如果页面上有 15 个产品,这是 0。

然后你有 ["href"] 它所做的只是获取该关键字中的数据,在这种情况下是相关产品页面的 url。

通过这种方法,你可以选择代码并粘贴,让它看起来像这样:

打印 item.contents[1].find_all("a", {"class":"a-link-normal s-access-detail-page a-text-normal"})[0]["href" ] print item.contents[1].find_all("a", {"class":"a-link-normal s-access-detail-page a-text-normal"})[1]["href"] print item.contents[1].find_all("a", {"class":"a-link-normal s-access-detail-page a-text-normal"})[2]["href"]

或者您可以找到一种方法,在一行代码中列出 X-Y 中的所有产品,这应该不难。

【讨论】:

    【解决方案2】:

    如果可行

    print item.contents[1].find_all("a", {"class": "a-link-normal"})[1]['href']

    这是正确的,您只需分配一个整数作为索引。我猜你想这样做。

    for item in g_data:
         print [item.contents[1].find_all("a", {"class": "a-link-normal"})[index]['href'] for index in [1,2,3]]
    

    【讨论】:

    • 我尝试了你的建议,但是由于 for 语句,它只会导致语法无效。
    • @JamieMumford 啊,对不起,我最后错过了一个右括号。我已经更正了,现在让我看看它是否有效。
    • 不,它也不起作用,出于某种原因,它是“for”语句。
    • 也许下次你应该用完整的数据结构更好地解释你的问题,而不是让人们猜测真正的问题是什么,并删除其他试图帮助的人的声誉。只是说。
    猜你喜欢
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2012-03-11
    • 2011-06-14
    • 2014-07-13
    • 1970-01-01
    相关资源
    最近更新 更多