#!/usr/bin/python
import requests
import random
def rewrite(ip):
return "{\'http\'"+":"+"\'http://"+ip+"\'}" #格式化代理
def req(url,p=None):
r = None
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) chrome/47.0.1453.110 Safari/5
37.36','Refefer':url}
s = requests.Session()
with open("/home/tech/proxyok","r") as f:
ips=f.read().strip('\n').split()
ipss = map(rewrite,ips)
proxy = random.choice(ipss)
if proxy:
try:
r = s.get(url,headers=headers,proxies=proxy,timeout=3)
except Exception,e:
print e
else:
try:
r = s.get(url,headers=headers)
except Exception,e:
print e
return r
if __name__ == "__main__":
print req('
http://baidu.com')
运行后报'str' object has no attribute 'get'
我以为是 requests.get 这个 get 的问题,后来把 try 去掉后,追踪到以下错误,但是我不明白是什么原因,新人,请指点一下,谢谢!
Traceback (most recent call last):
File "
httpreq.py", line 31, in <module>
print req('
http://xueqiu.com')
File "
httpreq.py", line 20, in req
r = s.get(url,headers=headers,proxies=p,timeout=3)
File "/usr/lib/python2.6/site-packages/requests/
sessions.py", line 310, in get
return self.request('GET', url, **kwargs)
File "/usr/lib/python2.6/site-packages/requests/
sessions.py", line 279, in request
resp = self.send(prep, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
File "/usr/lib/python2.6/site-packages/requests/
sessions.py", line 374, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python2.6/site-packages/requests/
adapters.py", line 155, in send
conn = self.get_connection(request.url, proxies)
File "/usr/lib/python2.6/site-packages/requests/
adapters.py", line 119, in get_connection
proxy = proxies.get(urlparse(url).scheme)
AttributeError: 'str' object has no attribute 'get'
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
https://www.v2ex.com/t/286527
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.