You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python requests报错AttributeError:'str'对象无get属性求助

问题解决:requests代理报错AttributeError: 'str' object has no attribute 'get'

错误原因

requests库的proxies参数要求传入字典类型,但你实际传入了字符串(random_proxy),导致内部调用proxies.get()时触发错误。从报错栈的代码行能看到,你在requests.get()里写的是proxies=random_proxy,和你贴出的代码定义的proxies字典不符,应该是实际运行的代码存在变量名写错或参数传错的问题。

修正步骤

  1. 规范代理字典格式:proxies字典的键要对应请求协议类型,http/https代理的标准结构如下:

    proxies = {
        'http': 'http://111.68.31.155:8080',
        'https': 'http://111.68.31.155:8080'
    }
    

    若从proxies.txt读取的代理是ip:port格式,需手动拼接协议前缀。

  2. 修正参数传递:确保requests.get()的proxies参数传入的是字典,而非字符串类型的代理地址。

  3. 完善代理读取逻辑:保证正确读取proxies.txt内容,过滤空行和换行符:

    def load_proxies():
        with open('proxies.txt', 'r') as f:
            return [line.strip() for line in f if line.strip()]
    

修正后的完整代码示例

import random
import requests
from threading import Thread, Lock

# 线程锁,避免多线程调用random.choice时出现异常
proxy_lock = Lock()
proxies_list = []

def load_proxies():
    global proxies_list
    with open('proxies.txt', 'r') as f:
        proxies_list = [line.strip() for line in f if line.strip()]

# 替换为你的实际cookies和headers
cookies = {}
headers = {}
t = 5  # 替换为你的线程数量

def main():
    while True:
        # 多线程环境下获取随机代理需加锁
        with proxy_lock:
            random_proxy = random.choice(proxies_list)
        # 构造符合要求的代理字典
        proxies = {
            'http': f'http://{random_proxy}',
            'https': f'http://{random_proxy}'
        }
        try:
            response = requests.get(
                'https://manacube.com/play/',
                cookies=cookies,
                proxies=proxies,
                headers=headers,
                timeout=10
            )
            if response.status_code == 200:
                print("Page View Sent (Code 200)")
            else:
                print(f"Error, Status Code: {response.status_code}")
        except Exception as e:
            print(f"Request Failed: {str(e)}")

if __name__ == "__main__":
    load_proxies()
    for x in range(int(t)):
        Thread(target=main).start()

额外注意事项

  • 多线程环境下使用random.choice必须加锁,避免多个线程同时操作导致的随机值异常。
  • 代理可能存在失效情况,添加异常捕获可避免单个代理错误导致线程崩溃。
  • 若使用socks5类型代理,需将字典键改为socks5,并安装依赖库:pip install requests[socks]。

内容的提问来源于stack exchange,提问作者lava gaming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 01:54:21