用requests爬虫拒绝301/302页面的重定向而拿到Location(重定向页面URL)的方法

2017-12-18 09:53:00
六月
来源:
http://blog.csdn.net/mao_code/article/details/54017708
转贴 1294

def yunsite():
    'url'
    headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
               'Accept-Encoding': 'gzip, deflate, sdch, br',
               'Accept-Language': 'zh-CN,zh;q=0.8',
               'Connection': 'keep-alive',
               'Host': 'pan.baidu.com',
               'Upgrade-Insecure-Requests': '1',
               'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}

    url = 'https://pan.baidu.com/s/1c0rjnbi'
    html = requests.get(url, headers=headers, allow_redirects=False)
    return html.headers['Location']

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

发表评论
评论通过审核后显示。