【发布时间】:2020-01-11 22:13:43
【问题描述】:
我正在尝试从我上面的 json 数据的 python 代码中访问某些变量。我对一起使用 python 和 json 很陌生,所以我不知道该怎么做。这是我的代码:
global proxy_addressed
ordered_proxies = []
for numb in range(0, num_tasks):
if numb % num_proxies == 0:
random.shuffle(add_proxy)
proxy_addressed = add_proxy[numb % num_proxies]
ordered_proxies.append(proxy_addressed)
global pvar
for lines in ordered_proxies:
pvar = lines.split(':') # rotating proxy or host
PROXY_HOST = pvar[0]
PROXY_PORT = pvar[1]
PROXY_USER = pvar[2]
PROXY_PASS = pvar[3]
print(PROXY_HOST)
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
background_js = """
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http","""
""" host: "{}",
port: "{}""""".format(PROXY_HOST, PROXY_PORT)
"""
},
bypassList: ["foobar.com"]
}
};
"""
"""
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {"""
""" username: "{}",
password: "{}""""".format(PROXY_USER, PROXY_PASS)
"""
}
};
}
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: PROXY_USER,
password: PROXY_PASS
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
"""
pluginfile = 'proxy_auth_plugin.zip'
with zipfile.ZipFile(pluginfile, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
co = Options()
co.add_argument("--start-maximized")
co.add_extension(pluginfile)
co.add_argument(win_size)
driver = webdriver.Chrome("chromedriver", chrome_options=co)
driver.execute_script("window.open('{}')".format(page_address))
我正在尝试在 manifest/background_json 中使用变量 PROXY_HOST、PROXY_PORT、PROXY_USER 和 PROXY_PASS,但没有成功。如何将代码中的变量调用到 json 中?
编辑:我应该更具体一点,我需要将代码输入到我编写的 js 脚本中,然后由 json 数据使用。所以真的就像我需要能够访问 js 脚本中的 python 变量。
编辑 2:我现在在控制台中遇到以前没有遇到的错误:
[22456:27868:0111/201424.041:ERROR:ssl_client_socket_impl.cc(935)] handshake failed; returned -1, SSL error code 1, net_error -201
编辑 3:上面的错误是因为我不小心将 PROXY_PASS 而不是 PROXY_PORT 放入需要端口的函数中。
【问题讨论】:
-
如果您有字符串,则使用字符串格式 - 即
"username: {}".format(PROXY_USER)或f-string- 即.f"username: {PROXY_USER}"
标签: javascript python json