1+ import os
12from typing import Annotated , Tuple
23from urllib .parse import urlparse , urlunparse
34
@@ -63,6 +64,37 @@ def get_robots_txt_url(url: str) -> str:
6364 return robots_url
6465
6566
67+ def normalize_proxy_url (proxy_url : str | None ) -> str | None :
68+ if proxy_url is None :
69+ return None
70+
71+ if proxy_url .lower ().startswith ("socks://" ):
72+ return f"socks5://{ proxy_url [len ('socks://' ):]} "
73+
74+ return proxy_url
75+
76+
77+ def proxy_url_for_request (url : str , proxy_url : str | None = None ) -> str | None :
78+ if proxy_url :
79+ return normalize_proxy_url (proxy_url )
80+
81+ scheme = urlparse (url ).scheme .lower ()
82+ proxy_keys = []
83+ if scheme == "https" :
84+ proxy_keys .extend (("HTTPS_PROXY" , "https_proxy" ))
85+ elif scheme == "http" :
86+ proxy_keys .extend (("HTTP_PROXY" , "http_proxy" ))
87+ proxy_keys .extend (("ALL_PROXY" , "all_proxy" ))
88+
89+ for key in proxy_keys :
90+ env_proxy = os .environ .get (key )
91+ normalized = normalize_proxy_url (env_proxy )
92+ if normalized != env_proxy :
93+ return normalized
94+
95+ return None
96+
97+
6698async def check_may_autonomously_fetch_url (url : str , user_agent : str , proxy_url : str | None = None ) -> None :
6799 """
68100 Check if the URL can be fetched by the user agent according to the robots.txt file.
@@ -72,7 +104,7 @@ async def check_may_autonomously_fetch_url(url: str, user_agent: str, proxy_url:
72104
73105 robot_txt_url = get_robots_txt_url (url )
74106
75- async with AsyncClient (proxy = proxy_url ) as client :
107+ async with AsyncClient (proxy = proxy_url_for_request ( robot_txt_url , proxy_url ) ) as client :
76108 try :
77109 response = await client .get (
78110 robot_txt_url ,
@@ -116,7 +148,7 @@ async def fetch_url(
116148 """
117149 from httpx import AsyncClient , HTTPError
118150
119- async with AsyncClient (proxy = proxy_url ) as client :
151+ async with AsyncClient (proxy = proxy_url_for_request ( url , proxy_url ) ) as client :
120152 try :
121153 response = await client .get (
122154 url ,
0 commit comments