簡體   English   中英

Python 類型的行然后循環遍歷它們直到行不在 txt 文件中

[英]Python type lines then loop over them till line not in txt file

我試圖記錄在我的請求期間使用的所有代理,所以我在接下來的幾個代理中沒有得到相同的,但由於某些原因它不起作用

這是記錄使用的代理的代碼

proxy_list = open('proxies.txt', 'a+')
    proxy_list.write(proxy)
    def renew_connection():
       with Controller.from_port(port = 9051) as controller:
           controller.authenticate(password="password")
           controller.signal(Signal.NEWNYM)
    renew_connection()
    session = get_tor_session()
    proxy1 = (session.get("http://api.ipify.org/").text)
    while proxy1 in proxy_list:
        def renew_connection():
          with Controller.from_port(port = 9051) as controller:
               controller.authenticate(password="password")
               controller.signal(Signal.NEWNYM)
        renew_connection()
        session = get_tor_session()
        proxy2 = (session.get("http://api.ipify.org/").text)
        if proxy2 not in proxy_list:
            break

編輯:

78.159.103.53
78.159.103.53
185.220.102.249
51.81.83.146
51.81.83.146
51.81.83.140
51.81.83.140
198.251.89.198
185.220.102.243
185.220.102.243
91.109.29.78
45.151.167.10

你的代碼的輸出

您的代碼不清楚,但我想我明白您要做什么。

  • 獲取使用的代理列表
  • 更新連接直到找到新的代理
  • 將新代理添加到使用列表

試試這個代碼:

def renew_connection():
   with Controller.from_port(port = 9051) as controller:
       controller.authenticate(password="password")
       controller.signal(Signal.NEWNYM)

with open('proxies.txt') as f:  # current proxy list
    proxy_list = f.readlines()

renew_connection()
session = get_tor_session()
proxy1 = (session.get("http://api.ipify.org/").text)

while proxy1 in proxy_list:
    renew_connection()
    session = get_tor_session()
    proxy1 = (session.get("http://api.ipify.org/").text)
        
with open('proxies.txt', 'a') as f:  # add new proxy
    f.write(proxy1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM