【问题标题】:How could I add list in list in code如何在代码中的列表中添加列表
【发布时间】:2018-05-20 11:01:06
【问题描述】:

我正在尝试对 Instagram 进行抓取,并且我已经实现了抓取的目标,但是我得到的结果是完美的,但我希望将它存储在列表中的列表中。

代码:-

Post links = ['https://www.instagram.com/p/BesW08pHfUt', 'https://www.instagram.com/p/BQZyTtej4yj']

      for post_link in post_links:
        _ = API.getMediaComments(get_media_id(post_link), max_id = 100)
        for c in reversed(API.LastJson['comments']):
            comment.append(c["user"]["username"])

我从 Instagram 的每个帖子链接中获得的 cmets

'https://www.instagram.com/p/BesW08pHfUt':-  'headhotel', 'famegalore', 'motivationpoem', 'malicioussatan'

'https://www.instagram.com/p/BQZyTtej4yj':- 'monarch_motivation', 'headhotel', 'motivationpoem'

我得到的输出

['headhotel', 'famegalore', 'motivationpoem', 'malicioussatan', 'monarch_motivation', 'headhotel', 'motivationpoem']

我想要的输出

[['headhotel', 'famegalore', 'motivationpoem', 'malicioussatan'], ['monarch_motivation', 'headhotel', 'motivationpoem']]

我知道这很简单,但我已经在 2 天内编写了这个爬虫代码,所以我有点困惑!

【问题讨论】:

  • 我们不知道你提到的 cmets 和输出来自哪里。您的代码 sn-p 描述性不够。
  • _ = API.getMediaComments(get_media_id(post_link), max_id = 100) 是做什么的?更准确地说,你为什么将调用的返回值存储在_ 中,然后不使用它?
  • @PM2Ring 从 Instagram 的帖子链接中获取 cmets
  • 如果您不需要调用的返回值,则不要分配它。只需API.getMediaComments(get_media_id(post_link), max_id = 100)
  • 进一步的代码中需要该代码,它与我的问题完全无关

标签: python python-3.x python-2.7 loops for-loop


【解决方案1】:

我不熟悉那个 API,但我认为你想做这样的事情:

for post_link in post_links:
    _ = API.getMediaComments(get_media_id(post_link), max_id = 100)
    sublist = []
    for c in reversed(API.LastJson['comments']):
        sublist.append(c["user"]["username"])
    comment.append(sublist)

这会在外部循环的每次迭代中创建一个新的子列表,内部循环将填充该子列表,然后我们将子列表附加到主 comment 列表中。

【讨论】:

    猜你喜欢
    • 2018-01-07
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    相关资源
    最近更新 更多