python3重定向
❶ python requests库如何处理302重定向
你的意思是希望requests报告302?
r = requests.get(url, allow_redirects=False)
r.status_code
r.headers['Location']
❷ python post 请求重定向怎么办
重定向与请求历史
默认情况下,除了 HEAD, Requests会自动处理所有重定向。
可以使用响应对象的 history 方法来追踪重定向。
Response.history 是一个:class:Response <requests.Response> 对象的列表,为了完成请求而创建了这些对象。
这个对象列表按照从最老到最近的请求进行排序。
例如,Github将所有的HTTP请求重定向到HTTPS。:
r = requests.get('')
r.url
r.status_code
r.history
如果你使用的是GET, OPTIONS, POST, PUT, PATCH 或者 DELETE,,那么你可以通过allow_redirects 参数禁用重定向处理:
r = requests.get('', allow_redirects=False)
r.status_code
r.history
如果你使用的是HEAD,你也可以启用重定向:
r = requests.head('', allow_redirects=True)
r.url
r.history
❸ python 爬网页 遇到重定向怎么处理
1.服务器端重定向,在服务器端完成,一般来说爬虫可以自适应,是不需要特别处理的,如响应代码301(永久重定向)、302(暂时重定向)等。具体来说,可以通过requests请求得到的response对象中的url、status_code两个属性来判断。当status_code为301、302或其他代表重定向的代码时,表示原请求被重定向;当response对象的url属性与发送请求时的链接不一致时,也说明了原请求被重定向且已经自动处理。
2.meta refresh,即网页中的<meta>标签声明了网页重定向的链接,这种重定向由浏览器完成,需要编写代码进行处理。例如,某一重定向如下面的html代码第三行中的注释所示,浏览器能够自动跳转,但爬虫只能得到跳转前的页面,不能自动跳转。
<html>
<head>
<metahttp-equiv="refresh"content="0.1;url=http://www..com/"><!--本网页会在0.1秒内refresh为url所指的网页-->
</head>
</html>
解决办法是通过得到跳转前的页面源码,从中提取出重定向url信息(上述代码第三行中的url属性值)。一个具体的操作:①使用xpath('//meta[@http-equiv="refresh" and @content]/@content')提取出content的值 ②使用正则表达式提取出重定向的url值。
3.js重定向,通过javaScript代码形式进行重定向。如下面javascript代码
<scriptlanguage=javascript>window.location.href='http://www..com'</script>
对于这种方式的跳转,由于可以实现该功能的JavaScript语句有多种形式,不能再使用正则表达式提取url,只能考虑加载JavaScript代码来进行解决。
❹ 关于python的输出重定向
importsys
f=open('a.txt','w')
print>>sys.stdout,'hello,world'
hello,world
print>>f,'hello,world'
f.close()
输出到屏幕的内容重定向到文件,供参考。
defprint(stream):
"""print(value,...,sep='',end='\n',file=sys.stdout)
Printsthevaluestoastream,ortosys.stdoutbydefault.
Optionalkeywordarguments:
file:afile-likeobject(stream);defaultstothecurrentsys.stdout.
sep:stringinsertedbetweenvalues,defaultaspace.
end:,defaultanewline."""
pass