如何将代理文件添加为字典格式

问题描述

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

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 文件添加每个代理?

解决方法

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

代理文本文件如下所示:

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']}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...