'str' object has no attribute 'get' 错误解决方案

我在使用python写爬虫时用到了requests.get()方法:

def openUrl(url, ip, agent):
    #函数形参为url:网页地址; ip:ip池; agent:User-Agent, 三者均为字符串类型
    requests.get(url, headers=agent, proxies=ip)

疑惑的是,使用时报了 ‘str’ object has no attribute ‘get’ 错误

查看文档后发现,是由于get()方法中的headers和proxies参数应传入字典而不是字符串,于是经修改,代码成功运行:

def openUrl(url, ip, agent):
    headers = {'User-Agent': agent}
    proxies = {'http' : ip}
    requests.get(url, headers=headers, proxies=proxies)

猜你喜欢

转载自www.cnblogs.com/yoyowin/p/12157800.html
今日推荐