사용자가 게임 내 링크를 열면 자동으로 "지도"를 다운로드하는 작은 스크립트를 만들고 싶었습니다. 링크가 크롬에서 열리면 확장 프로그램은 현재 URL을 가져 와서 파이썬으로 보낸 다음 (지금 당장 멈춰있는 곳입니다) 성공하면 탭을 닫습니다 (파이썬 스크립트가 실행되지 않으면 실패하기 때문에? ). 파이썬에서 한 번 나는 문제의지도를 다운로드하고 노래 폴더에 추가하여 그가 할 유일한 일은 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);
}
})
링크를 수신하고 "지도"를 다운로드하는 스크립트 :
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 검색 중 하나에서 왔지만 파이썬에서 POST 요청을 처리하는 방법을 이해하지 못하며 올바른 방법으로 가고 있는지조차 모릅니다.
어떤 사람들은 내가이 주제에 대해 많은 연구를하지 않았다고 말할지 모르지만 약 50 개의 크롬 탭 중에서이 주제에 대한 올바른 접근 방식에 대한 아이디어를 실제로 찾을 수있는 것은 없습니다.
웹 서버를 실행해야 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", "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()
(old 대신 XMLHttpRequest()
)를 사용하고 페이지를 다시로드하지 않습니다.
javascript:{fetch('http://localhost:5000/?data='+encodeURIComponent(window.location.href))}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다