我正在编写一个网络抓取工具,基本上我正在使用 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/