需要关于将变量从chrome扩展发送到python的帮助吗

2024-05-23 14:01:51 发布

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

我想制作一个小脚本,当用户打开ingame链接时自动下载“地图”。 一旦链接在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
}

奥苏!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标签中,我还没有找到任何真正能让我对这一主题的正确方法有想法的东西


Tags: import脚本trueurl链接as地图link
1条回答
网友
1楼 · 发布于 2024-05-23 14:01:51

您必须运行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))}

相关问题 更多 >