如何安装Sgrequests模块?运行代码遇ModuleNotFoundError
解决ModuleNotFoundError: No module named 'sgrequests'问题
sgrequests并非公开PyPI仓库中的标准模块,从代码里的用法(指定代理国家、自定义重试状态码)来看,它是一个基于requests封装的自定义工具模块,用于处理代理请求和重试逻辑。以下是两种解决思路:
一、用标准库+第三方替代方案实现相同功能
不需要寻找sgrequests,直接用requests配合重试库实现相同逻辑:
- 先安装依赖:
pip install requests tenacity
- 修改代码:
- 替换导入部分:
# 替换原有的from sgrequests import SgRequests import requests from tenacity import retry, stop_after_attempt, retry_if_exception_type, retry_if_result from requests.exceptions import RequestException class CustomSession(requests.Session): def __init__(self, proxy_country=None, dont_retry_status_codes_exceptions=None): super().__init__() # 配置US代理(和你代码里的一致) if proxy_country == "us": self.proxies = { 'http': 'http://37.48.118.90:13042', 'https': 'https://37.48.118.90:13042' } self.dont_retry_codes = dont_retry_status_codes_exceptions or set() @retry(stop=stop_after_attempt(3), retry=(retry_if_exception_type(RequestException) | retry_if_result(lambda resp: resp.status_code not in self.dont_retry_codes and 500 <= resp.status_code < 600))) def get(self, url, **kwargs): resp = super().get(url, **kwargs) if resp.status_code in self.dont_retry_codes: raise RequestException(f"状态码{resp.status_code}不重试") resp.raise_for_status() return resp - 替换session初始化:
# 替换原有的session = SgRequests(...) session = CustomSession(proxy_country="us", dont_retry_status_codes_exceptions=set([403, 407, 503]))
- 替换导入部分:
二、获取原始的sgrequests模块
如果这个模块是某个私有项目或内部工具:
- 检查代码所在的项目目录,看是否有
sgrequests.py文件,把它放到你的脚本同一目录下即可直接导入。 - 联系代码提供者获取该模块的安装包或仓库地址。
额外代码问题提示
你的代码里还有两处错误需要修正:
goelocator拼写错误,应该是geolocator。start_requests方法里使用了location.latitude但未定义location变量,需要先通过地理编码获取坐标:# 在循环内添加 location = geolocator.geocode(holder_name) if not location: print(f"无法获取{holder_name}的坐标,跳过") continue
内容的提问来源于stack exchange,提问作者AbdulRafay Zafar
相关产品推荐
相关产品推荐

