需要有关将变量从 chrome 扩展发送到 python 的帮助
Need help about sending variable from chrome extension to python
我想制作一个小脚本,当用户打开游戏时自动下载“地图”link。
一旦 link 在 chrome 中打开,扩展程序获取当前 URL 并将其发送到 python(这是我现在卡住的地方),然后关闭选项卡如果成功(因为如果 python 脚本不是 运行,它将失败?)。
在 python 之后,我继续下载有问题的地图并将其添加到 Songs 文件夹中,他唯一要做的就是按 F5
现在,我有这些代码:
Manifest.json:
{
"name": "Osu!AltDownload",
"version": "1.0",
"description": "A requirement to make osu!AltDownload work",
"permissions": ["tabs","http://localhost:5000/"],
"background": {
"scripts": ["Osu!AltDownload.js"],
"persistant": false
},
"manifest_version": 2
}
Osu!AltDownload.js
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
let url = tabs[0].url;
});
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:5000/",true);
xhr.send(url);
}
})
接收 links 并下载“地图”的脚本:
import browser_cookie3
import requests
from bs4 import BeautifulSoup as BS
import re
import os
def maplink(osupath):
link = link #obtain link from POST ?
if link.split("/",4[:4]) == ['https:', '', 'osu.ppy.sh', 'beatmapsets']:
Download_map(osupath, link.split("#osu")[0])
def Download_map(osupath, link):
cj = browser_cookie3.load()
print("Downloading", link)
headers = {"referer": link}
with requests.get(link) as r:
t = BS(r.text, 'html.parser').title.text.split("·")[0]
with requests.get(link+"/download", stream=True, cookies=cj, headers=headers) as r:
if r.status_code == 200:
try:
id = re.sub("[^0-9]", "", link)
with open(os.path.abspath(osupath+"/Songs/"+id+" "+t+".osz"), "wb") as otp:
otp.write(r.content)
except:
print("You either aren't connected on osu!'s website or you're limited by the API, in which case you now have to wait 1h and then try again.")
我想补充一点,我在我的扩展中使用了这些代码行:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:5000/",true);
xhr.send(url);
它们来自我的一个 google 搜索,但我真的不明白我如何处理 python 中的 POST 请求,我什至不知道是否我走对了。
有些人可能会说我没有对这个主题做太多研究,但是在大约 50 个 chrome 选项卡中,我还没有真正找到任何能让我真正了解正确方法的东西主题。
您必须 运行 网络服务器才能获得 http requests
您可以为此使用 Flask
。
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
#print(request.form)
print(request.data)
return "OK"
if __name__ == '__main__':
app.run(port=5000)
如果您只想发送 url
那么您甚至可以使用 GET
而不是 POST
并发送为
http://localhost:5000/?data=your_url
其中 your_url
是您使用 tab[0].url
获得的结果。
xhr.open("GET", "http://localhost:5000/?data=" + url, true);
xhr.send(); // or maybe xhr.send(null);
然后你可以用
得到它
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
print(request.args.get('data'))
return "OK"
if __name__ == '__main__':
app.run(port=5000)
编辑:
当您访问 http://localhost:5000/test
时直接使用 JavaScript
测试 Flask
的示例
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
print(request.args.get('data'))
return "OK"
@app.route('/test/')
def test():
return """
<script>
var url = "https://whosebug.com/questions/65867136/need-help-about-sending-variable-from-chrome-extension-to-python/";
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:5000/?data=" + url, true);
xhr.send();
</script>
"""
if __name__ == '__main__':
app.run(port=5000)
最终我可以用 bookmarklet
来测试它
javascript:{window.location='http://localhost:5000/?data='+encodeURIComponent(window.location.href)}
我将其作为 url 放入收藏夹的书签中 - 但此重新加载页面
或使用现代 fetch()
(而不是旧 XMLHttpRequest()
)并且它不会重新加载页面。
javascript:{fetch('http://localhost:5000/?data='+encodeURIComponent(window.location.href))}
我想制作一个小脚本,当用户打开游戏时自动下载“地图”link。 一旦 link 在 chrome 中打开,扩展程序获取当前 URL 并将其发送到 python(这是我现在卡住的地方),然后关闭选项卡如果成功(因为如果 python 脚本不是 运行,它将失败?)。 在 python 之后,我继续下载有问题的地图并将其添加到 Songs 文件夹中,他唯一要做的就是按 F5
现在,我有这些代码:
Manifest.json:
{
"name": "Osu!AltDownload",
"version": "1.0",
"description": "A requirement to make osu!AltDownload work",
"permissions": ["tabs","http://localhost:5000/"],
"background": {
"scripts": ["Osu!AltDownload.js"],
"persistant": false
},
"manifest_version": 2
}
Osu!AltDownload.js
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
let url = tabs[0].url;
});
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:5000/",true);
xhr.send(url);
}
})
接收 links 并下载“地图”的脚本:
import browser_cookie3
import requests
from bs4 import BeautifulSoup as BS
import re
import os
def maplink(osupath):
link = link #obtain link from POST ?
if link.split("/",4[:4]) == ['https:', '', 'osu.ppy.sh', 'beatmapsets']:
Download_map(osupath, link.split("#osu")[0])
def Download_map(osupath, link):
cj = browser_cookie3.load()
print("Downloading", link)
headers = {"referer": link}
with requests.get(link) as r:
t = BS(r.text, 'html.parser').title.text.split("·")[0]
with requests.get(link+"/download", stream=True, cookies=cj, headers=headers) as r:
if r.status_code == 200:
try:
id = re.sub("[^0-9]", "", link)
with open(os.path.abspath(osupath+"/Songs/"+id+" "+t+".osz"), "wb") as otp:
otp.write(r.content)
except:
print("You either aren't connected on osu!'s website or you're limited by the API, in which case you now have to wait 1h and then try again.")
我想补充一点,我在我的扩展中使用了这些代码行:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:5000/",true);
xhr.send(url);
它们来自我的一个 google 搜索,但我真的不明白我如何处理 python 中的 POST 请求,我什至不知道是否我走对了。
有些人可能会说我没有对这个主题做太多研究,但是在大约 50 个 chrome 选项卡中,我还没有真正找到任何能让我真正了解正确方法的东西主题。
您必须 运行 网络服务器才能获得 http requests
您可以为此使用 Flask
。
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
#print(request.form)
print(request.data)
return "OK"
if __name__ == '__main__':
app.run(port=5000)
如果您只想发送 url
那么您甚至可以使用 GET
而不是 POST
并发送为
http://localhost:5000/?data=your_url
其中 your_url
是您使用 tab[0].url
获得的结果。
xhr.open("GET", "http://localhost:5000/?data=" + url, true);
xhr.send(); // or maybe xhr.send(null);
然后你可以用
得到它from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
print(request.args.get('data'))
return "OK"
if __name__ == '__main__':
app.run(port=5000)
编辑:
当您访问 http://localhost:5000/test
JavaScript
测试 Flask
的示例
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def index():
print(request.args.get('data'))
return "OK"
@app.route('/test/')
def test():
return """
<script>
var url = "https://whosebug.com/questions/65867136/need-help-about-sending-variable-from-chrome-extension-to-python/";
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:5000/?data=" + url, true);
xhr.send();
</script>
"""
if __name__ == '__main__':
app.run(port=5000)
最终我可以用 bookmarklet
javascript:{window.location='http://localhost:5000/?data='+encodeURIComponent(window.location.href)}
我将其作为 url 放入收藏夹的书签中 - 但此重新加载页面
或使用现代 fetch()
(而不是旧 XMLHttpRequest()
)并且它不会重新加载页面。
javascript:{fetch('http://localhost:5000/?data='+encodeURIComponent(window.location.href))}