我正试图使我的结果类似于:
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']}