Python在浏览器中使用代理打开web链接

2024-04-19 20:40:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写python程序,在googlechrome/macOS中打开一个链接,但是我需要从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)

以下是收到评论后的更新代码:

^{pr2}$

但是我收到了以下错误:

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'

Tags: 文件代码importbrowserchildurltimeos
1条回答
网友
1楼 · 发布于 2024-04-19 20:40:31

不要使用shell=True。相反,尝试直接执行googlechrome而不执行shell。如果可以直接调用所需程序,则无需调用shell进程来执行程序:

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)

通过不使用shell,您还可以使用.terminate()来终止子进程-不需要运行killall,因为您正在运行的进程实际上是您想要终止的进程,而不是shell。在

相关问题 更多 >