【问题标题】:iterate two list with different size迭代两个不同大小的列表
【发布时间】:2018-07-17 09:15:23
【问题描述】:
import itertools
Value = ['178.217.107.8:53281', '91.90.191.238:8080', '27.116.51.114:8080']
content = ['link1','link2','link3']

for a,b in zip(Value , itertools.cycle(content)):
   print(a,b)

我正在寻找的是,如果在第一个列表(代理列表)中假设任何代理不起作用,然后传递并移动到列表中的下一个,平行于内容列表中的元素当前阶段应该保持不变。

例如: 对于第一个元素,输出为: 178.217.107.8:53281 链路1

但如果 178.217.107.8:53281 抛出错误,则将循环中的“a”值作为 并将输出作为 91.90.191.238:8080 Link1

【问题讨论】:

  • @blhsing 如果你能帮忙
  • @blhsing 你能帮忙吗

标签: python-3.x selenium-webdriver web-scraping proxy


【解决方案1】:

伪代码如下:

list_of_proxies = ['178.217.107.8:53281', '91.90.191.238:8080', '27.116.51.114:8080']
list_of_links = ['link1','link2','link3']
for proxy in list_of_proxies:
    for link in list_of_links:
        # call some method to check if the proxy worked and store in a variable
        success = method_call(proxy, link) # assuming return type as boolean
        if !success:
            break
        else:
            # remove the successful link from the list, depending on your exact requirement
            list_of_links.remove(link)

【讨论】:

  • 我不想使用 nesed for 循环,而是想同时迭代两个列表,这是使用 zip 方法完成的,但唯一的问题是,如果一个列表中的元素之一抛出错误移动到两个列表中元素的下一个索引,而不是我想移动到引发错误的列表元素的下一个索引
  • 因为对于代理列表中的每个代理,它将迭代链接列表中的所有元素,但我想同时迭代一个代理和一个链接
【解决方案2】:

在这种情况下,您需要遍历您的链接,并且对于每个链接,使用 itertools.cycle 在代理列表中循环,直到您成功获取链接。

伪代码:

from itertools import cycle
Value = ['178.217.107.8:53281', '91.90.191.238:8080', '27.116.51.114:8080']
content = ['link1','link2','link3']
proxies = cycle(Value)

for link in content:
    while True:
        response = get_link_via_proxy(link, next(proxies))
        if response.is_success:
           break
    do_something_with(response)

【讨论】:

  • 我想同时迭代一个代理和一个链接,基本上我想使用不同的代理 IP 打开每个下一个链接
  • 我明白了。您需要使用itertools.cycle,然后使用next 获取列表中的下一个代理。我已经相应地更新了我的答案。
  • 感谢您在上面的伪代码中提供的帮助,但无法有效地实现它,因此我已经粘贴了整个代码 stackoverflow.com/questions/51397614/… 如果您可以查看它并进行相应的编辑并帮助我
猜你喜欢
  • 1970-01-01
  • 2016-08-28
  • 2016-08-02
  • 1970-01-01
  • 2016-07-11
  • 2022-11-03
  • 2017-10-15
  • 2019-11-10
  • 1970-01-01
相关资源
最近更新 更多