【问题标题】:How can I add a file of proxies into dictionary format如何将代理文件添加到字典格式
【发布时间】:2021-06-06 18:30:29
【问题描述】:

我正在尝试使我的结果类似于:

proxies_dict = {
   'http':'http://178.141.249.246:8081',
   'http':'http://103.12.198.54:8080',
   'http':'http://23.97.173.57:80',
}

我试过了

proxies_dict = {}

with open('proxies.txt', 'r') as proxy_file:
    for proxy in proxy_file:
        proxies_dict['http'] = 'http://' + proxy.rstrip()

print(proxies_dict)

但这只会添加代理的最后一行,而不是全部。如何让它在我的 .txt 文件中添加每个代理?

【问题讨论】:

  • 字典中的键必须是唯一的。您应该将链接设置为它们的列表,例如{‘http’: [link1,…,linkn]}
  • 我该如何解决? @David 我逻辑很烂
  • 除了http,您还使用其他密钥吗?

标签: arrays python-3.x dictionary python-requests proxies


【解决方案1】:

这样的事情可以让你继续前进!

代理文本文件如下所示:

178.141.249.246:8081
103.12.198.54:8080
23.97.173.57:80

proxies_list = []


with open('proxies.txt', 'r+') as proxy_file:
    
    # read txt file 
    proxies = proxy_file.readlines()
    
    for proxy in proxies:

        # initialize dict in loop 
        proxies_dict = {}

        # add proxy to dict 
        proxies_dict['http'] = 'http://' + proxy.rstrip()

        # append dict to list 
        proxies_list.append(proxies_dict)

print(proxies_dict)

[{'http': 'http://178.141.249.246:8081'},
 {'http': 'http://103.12.198.54:8080'},
 {'http': 'http://23.97.173.57:80'}]

基本上,您必须先读取文件,然后在将项目添加到字典时将其附加到将包含每个代理的列表中。我这样做是为了让您可以为每个代理保留“http”键。

编辑

如果您需要将它们全部放在一本字典中,那么根据大卫的回答,它会看起来有链接:

with open(file, 'r+') as f: 
    
    # read file 
    content = f.readlines()
 
    # this is an extra step for if you want to 
    # strip the newlines from each item, else 
    # links = content 
    # will work as well 
  
    links = [row.strip() for row in content] 
    
    # initialize dict 
    tmp = {}
    
    # create http key and and links list 
    tmp['http'] = links 
    
    # print result
    print(tmp)

{'http': ['178.141.249.246:8081', '103.12.198.54:8080', '23.97.173.57:80']}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-19
    • 2015-06-24
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多