我正在编写在Google Chrome / macOS中打开链接的python程序,但是在打开链接时,我需要遍历proxylist.txt文件中的代理列表。
在浏览器中打开链接时,是否有任何方法可以强制特定代理?以及何时使用子流程模块?
这是我的代码:
import os
import subprocess as sp
import time
def browse(url, dur):
browser = "open -a 'Google Chrome'"
child = sp.Popen(browser+" %s" % url, shell=True)
time.sleep(int(dur))
child.terminate()
os.system("killall -9 'Google Chrome'")
url_link = input("Enter link: ")
duration = input("Enter duration in seconds: ")
browse(url_link, duration)
以下是收到评论后的更新代码:
import subprocess as sp
import time
def browse(url, dur, proxy_host, proxy_port):
browser = ['google-chrome', url,
'--proxy-server={host}:{port}'.format(host=proxy_host, port=proxy_port)]
child = sp.Popen(browser)
time.sleep(int(dur))
child.terminate()
url_link = input("Enter link: ")
duration = input("Enter duration in seconds: ")
with open("proxylist.txt", "r") as file:
for line in file:
line = line.rstrip()
myProxy = line.split(':')[0]
myPort = line.split(':')[1]
counter = 1
while (counter <= 10):
print("Count: " + str(counter) + ", opening link " + url_link + " -- proxy id: " + myProxy + ":" + myPort)
browse(url_link, duration, myProxy, myPort)
counter += 1
但是我收到以下错误:
File "/xxxxx/subprocess.py", line 1344, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'google-chrome': 'google-chrome'
答案 0 :(得分:1)
请勿使用body {
display: grid;
grid-template-columns: repeat(5, 20%);
grid-column-gap: 0px;
justify-items: center;
}
。而是尝试直接执行Google chrome,而不执行Shell。当您可以直接调用所需的程序时,无需调用Shell进程来执行程序:
shell=True
通过不使用外壳,您还可以使用import os
import subprocess as sp
import time
def browse(url, dur, proxy_host, proxy_port):
browser = ['google-chrome', url,
'--proxy-server={host}:{port}'.format(host=proxy_host, port=proxy_port)]
child = sp.Popen(browser)
time.sleep(int(dur))
child.terminate()
url_link = input("Enter link: ")
duration = input("Enter duration in seconds: ")
browse(url_link, duration, 'my_proxy', 1234)
终止子进程-无需运行.terminate()
,因为您正在运行的进程实际上是您要终止的进程,而不是外壳