我正在编写一个网络抓取工具,基本上我正在使用 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 它会起作用,但它会下载文件两次。有没有办法不用下载就可以得到重定向的url?
已解决 最终代码如下所示,谢谢!
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']
