问题描述
我想制作一个小脚本,当用户打开游戏链接时自动下载“地图”。 一旦链接在 chrome 中打开,扩展程序将获取当前 URL 并将其发送到 python(这是我现在卡住的地方),然后如果成功则关闭选项卡(因为如果 python 脚本没有运行它会失败? )。 一旦在python中,我然后继续下载有问题的地图并将其添加到Songs文件夹中,他唯一要做的就是按F5
Manifest.json:
OrderSerializer instanceof serializers.ModelSerializer
Osu!AltDownload.js
{
"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
}
接收链接并下载“地图”的脚本:
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);
}
})
我想补充一点,我在扩展程序中使用了这些代码行:
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.")
它们来自我的一次谷歌搜索,但我真的不明白我如何用它在 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)
编辑:
在您访问 Flask
时直接使用 JavaScript
测试 http://localhost:5000/test
的示例
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://stackoverflow.com/questions/65867136/need-help-about-sending-variable-from-chrome-extension-to-python/";
var xhr = new XMLHttpRequest();
xhr.open("GET",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))}