[英]Need help about sending variable from chrome extension to python
我想制作一個小腳本,當用戶打開游戲鏈接時自動下載“地圖”。 一旦鏈接在 chrome 中打開,擴展程序會獲取當前的 URL 並將其發送到 python(這是我現在卡住的地方),然后如果成功則關閉選項卡(因為如果 python 腳本沒有運行,它將失敗? )。 一旦在 python 我然后繼續下載有問題的 map 並將其添加到 Songs 文件夾中,他唯一要做的就是按 F5
現在,我有這些代碼:
清單.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);
}
})
接收鏈接並下載“地圖”的腳本:
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);
它們來自我的谷歌搜索之一,但我真的不明白如何處理 python 中的 POST 請求,我什至不知道我是否走對了路。
有人可能會說我在這個主題上沒有做太多研究,但是在大約 50 個 chrome 標簽中,我還沒有真正找到任何能讓我真正了解這個主題的正確方法的東西。
您必須運行 web 服務器才能獲取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://stackoverflow.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))}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.