python重定向cookie_python requests 301/302/303重定向cookie和Location问题

Simple One:适用cookie 不会变化的情形

import requests

params = {'username': 'Ryan',

'password': 'password'}

r = requests.post("http://pythonscraping.com/pages/cookies/welcome.php", data=params)

print "Cookie is set to:"

print r.cookies.get_dict()

print "-----------------"

print "Going to profile page..."

r = requests.get("http://pythonscraping.com/pages/cookies/profile.php", cookies = r.cookies)

print r.text

Complex One:适用于cookie可能会被修改的情况下, 使用request.Session

import requests

sess = requests.Session()

params = {'username': 'Ryan',

'password': 'password'}

s = sess.post("http://pythonscraping.com/pages/cookies/welcome.php", data=params)

print "Cookie is set to:"

print s.cookies.get_dict()

print "----------------"

print "Going to profile page..."

s = sess.get("http://pythonscraping.com/pages/cookies/profile.php")

print s.text

跨请求保持一些 cookie

在爬取网页时,要注意返回的response里是否有Location,如果有Location就意味着可能会有跳转,即重定向

原文如下:

今天使用request的get方法获取一个网站的登录页信息,结果使用charles抓包的时候发现该网站登录页303(重定向的问题),网上查了很多资料,原因如下:

一、 Cookie

原因:利用requests模拟登录时,直接使用request.get(url),容易造成 301/302/303 重定向,因为cookie不持久,造成重定向之后的cookie等信息获取不到

(1) 同一个Host下边重定向

解决方法:使用requests.Session()方法,会使该连接持久化,并且保存请求的状态(session、cookie等),这样在重定向之后,我们使用requests.cookies就能获取到cookie了

result = requests.Session()

header = {

'Host' : 'xxxxx',

'Accept' : 'xxxx',

'User-Agent': 'xxxx'

}

response = result.get(url, headers=header)

注意:上面讲的重定向是在同一个host下重定向,跨域的重定向用上边的方法就获取不到cookie

(2) 跨域重定向# 获取请求url域名

def (url):

pattern = re.compile(r'(.*?)://(.*?)/', re.S)

response = re.search(pattern, url)

if response:

return {'header':str(response.group(1)).strip(), 'host': str(response.group(2)).strip()}

else:

return None

cookieType = {} # 保存域名对应的cookie

def getRedirectCookie(url):

locationList = set()

cookie = ''

resUrl = url # 获取最后请求url

header = {

'User-Agen': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'

}

try:

while True:

# 请求

response = requests.get(url, headers=header, allow_redirects=False)

# 获取host

hostObj = getHost(resUrl)

if hostObj is None:

return None

# 处理cookie

cookie = response.cookies.get_dict()

if cookie == {}:

pass

else:

cookieType[str(hostObj['host']).strip()] = json.dumps(cookie) # 保存cookie

# 获取跳转的url

if 'Location' in response.headers.keys():

url = response.headers.get('Location')

if not 'http' in url:

url = hostObj['header'] + '://' + hostObj['host'] + url # 拼接host域名

resUrl = url

if url in locationList: break

locationList.add(url)

else:

break

return {'url': str(resUrl), 'content': response.content, 'header': response.headers}

except urllib2.URLError, e:

if hasattr(e, 'reason'):

print '请求失败,原因:' + e.reason

return None

注意: 有时候执行带有重定向的时候会出现:”requests.exceptions.TooManyRedirects: Exceeded 30 redirects.”的情况,那么这时候是说重定向次数上限了,也可以使用上边的这种方式来解决

Location(重定向url):获取重定向url

有时候遇到重定向,我们只需要获取重定向的url即可,这个时候使用上述方法开启一个保持状态的长连接,并请求时获取不到的请求的headers的,那么我们该怎么办呢?

解决:

result = requests.Session()

header = {

'Host' : 'xxxxx',

'Accept' : 'xxxx',

'User-Agent': 'xxxx'

}

response = result.get(url, headers=header, allow_redirects=False)

location = response.headers['Location'] # 注意有些header返回的Location中的url是不带host部分的,需要注意一下

allow_redirects=False 的意义为拒绝默认的301/302/303重定向从而可以通过response.headers[‘Location’]拿到重定向的URL。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值