python - 如何在不下载文件的情况下获取重定向的 URL

标签 python python-2.7 python-requests

我正在编写一个网络抓取工具,基本上我正在使用 requests 和 bs4 处理的是一个提供 https://downlaod.domain.com/xid_39428423_1 样式的所有内容的网站。然后将您重定向到实际文件。我想要的是一个在下载文件之前获取重定向链接的命令,这样我就可以检查是否已经下载了所述文件。我当前的代码片段是这样的:

def download_file(file_url,s,thepath):
    if not os.path.isdir(thepath):
        os.makedirs(thepath)
    print 'getting header'
    i = s.head(file_url)
    urlpath = i.url
    name = urlsplit(urlpath)[2].split('/')
    name = name[len(name)-1]
    if not os.path.exists(thepath + name):
        print urlpath
        i = s.get(urlpath)
        if i.status_code == requests.codes.ok:
            with iopen(thepath + name, 'wb') as file:
                file.write(i.content)
        else:
            return False

如果我将 s.head 更改为 s.get 它可以工作,但它会下载文件两次。有什么方法可以在不下载的情况下获取重定向的网址吗?

已解决 最终代码如下所示,谢谢!

def download_file(file_url,s,thepath):
    if not os.path.isdir(thepath):
        os.makedirs(thepath)
    print 'getting header'
    i = s.get(file_url, allow_redirects=False)
    if i.status_code == 302:
        urlpath = i.headers['location']
    else: 
        urlpath = file_url
    name = urlsplit(urlpath)[2].split('/')
    name = name[len(name)-1]
    if not os.path.exists(thepath + name):
        print urlpath
        i = s.get(urlpath)
        if i.status_code == requests.codes.ok:
            with iopen(thepath + name, 'wb') as file:
                file.write(i.content)
        else:
            return False

最佳答案

您可以使用 allow_redirects 标志并将其设置为 False (请参阅 the documentation )。这样 .get() 将不会遵循重定向,这允许您在检索文件本身之前检查响应。

换句话说,而不是这个:

i = s.head(file_url)
urlpath = i.url

你可以写:

i = s.get(file_url, allow_redirects=False)
urlpath = i.headers['location']

关于python - 如何在不下载文件的情况下获取重定向的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20049729/

相关文章:

python - 如何从 flask 发送和接收数据?

Python 请求无法解码文本

python - 你怎么称呼模块的元素?

Python MySQLdb TypeError : not all arguments converted during string formatting

Python - 从列表中删除键/值元素并返回新列表

python - 从源代码安装 python3.5 后如何修复 virtualenv 的 python pip 段错误(核心转储)响应

python - Spotify 授权代码(不是访问 token )即将过期 - 我该如何规避此问题?

python - Django - 渲染存储在数据库字段中的变量

python - 在 numpy 二维数组中计算大于的最佳方法

python 正则表达式帮助 : match all text between '"icon":"' AND '.png", '