Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

windows - How can i use my python script as proxy for urls

i have a script that check the input link, if it's equivalent to one i specified in the code, then it will use my code, else it open the link in chrome.

i want to make that script kind of as a default browser, as to gain speed compared to opening the browser, getting the link with an help of an extension and then send it to my script using POST.

i used procmon to check where the process in question query the registry key and it seem like it tried to check HKCUSoftwareClassesChromeHTMLshellopencommand so i added a some key there and in command, i edited the content of the key with my script path and arguments (-- %1)(-- only here for testing purposes) unfortunately, once the program query this to send a link, windows prompt to choose a browser instead of my script, which isn't what i want. Any idea?

question from:https://stackoverflow.com/questions/65888921/how-can-i-use-my-python-script-as-proxy-for-urls

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

in HKEY_CURRENT_USERSoftwareClassesChromeHTMLShellopencommand Replace the value in default with "C:Userssamdra.rAppDataLocalProgramsPythonPython39pythonw.exe" "[Script_path_here]" %1

when launching a link, you'll be asked to set a default browser only once (it ask for a default browser for each change you make to the key): i select chrome in my case

as for the python script, here it is:

import sys
import browser_cookie3
import requests
from bs4 import BeautifulSoup as BS
import re
import os
import asyncio
import shutil

def Prep_download(args):
    settings = os.path.abspath(__file__.split("NewAltDownload.py")[0]+'/settings.txt')
    if args[1] == "-d" or args[1] == "-disable":
        with open(settings, 'r+') as f:
            f.write(f.read()+"
"+"False")
            print("Background program disabled, exiting...")
            exit()
    if args[1] == "-e" or args[1] == "-enable":
        with open(settings, 'r+') as f:
            f.write(f.read()+"
"+"True")
    link = args[-1]
    with open(settings, 'r+') as f:
        try:
            data = f.read()
            osupath = data.split("
")[0]
            state = data.split("
")[1]
        except:
            f.write(f.read()+"
"+"True")
            print("Possible first run, wrote True, exiting...")
            exit()
    if state == "True":
        asyncio.run(Download_map(osupath, link))

async def Download_map(osupath, link):
    if link.split("/")[2] == "osu.ppy.sh" and link.split("/")[3] == "b" or link.split("/")[3] == "beatmapsets":
        with requests.get(link) as r:
            link = r.url.split("#")[0]
        BMID = []
        id = re.sub("[^0-9]", "", link)
        for ids in os.listdir(os.path.abspath(osupath+("/Songs/"))):
            if re.match(r"(^d*)",ids).group(0).isdigit():
                BMID.append(re.match(r"(^d*)",ids).group(0))
        if id in BMID:
            print(link+": Map already exist")
            os.system('"'+os.path.abspath("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe")+'" '+link)
            return
        if not id.isdigit():
            print("Invalid id")
            return
        cj = browser_cookie3.load()
        print("Downloading", link, "in", os.path.abspath(osupath+"/Songs/"))
        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(__file__.split("NewAltDownload.pyw")[0]+id+" "+t+".osz"), "wb") as otp:
                        otp.write(r.content)
                    shutil.copy(os.path.abspath(__file__.split("NewAltDownload.pyw")[0]+id+" "+t+".osz"),os.path.abspath(osupath+"/Songs/"+id+" "+t+".osz"))
                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.")
    else:
        os.system('"'+os.path.abspath("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe")+'" '+link)

args = sys.argv
if len(args) == 1:
    print("No arguments provided, exiting...")
    exit()
Prep_download(args)

you obtain the argument %1 (the link) with sys.argv()[-1] (since sys.argv is a list) and from there, you just check if the link is similar to the link you're looking for (in my case it need to look like https://osu.ppy.sh/b/ or https://osu.ppy.sh/beatmapsets/) if that's the case, do some code, else, just launch chrome with chrome executable and the link as argument. and if the id of the beatmap is found in the Songs folder, then i also open the link in chrome.

to make it work in the background i had to fight with subprocesses and even more tricks, and at the end, it started working suddenly with pythonw and .pyw extension.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...