如何在Python中从网页转义图像/文件?

问题描述 投票:0回答:1

我尝试使用Python3.7.4备份博客网站中的图片,例如http://s2.sinaimg.cn/mw690/001H6t4Fzy7zgC0WLXb01&690如果我在Firefox地址栏中输入上述地址,则该文件将正确显示。如果我使用以下代码下载图片,服务器将始终重定向到默认图片:

from requests import get # just to try different methods
from urllib.request import urlopen
from urllib.parse import urlsplit, urlunsplit, quote

# hard-coded address is randomly selected for debug purpose.
origPict = 'http://s2.sinaimg.cn/mw690/001H6t4Fzy7zgC0WLXb01&690' 
p = urlsplit (origPict)
newP = quote (p.path)
origPict = urlunsplit ([p.scheme, p.netloc, newP, p.query, p.fragment])

try:
  #url_file = urlopen(origPict)
  #u = url_file.geturl ()
  url_file = get (origPict)
  u = url_file.url
  if u != origPict:
    raise Exception ('Failed to get picture ' + origPict)
...

任何线索为什么requests.get或urllib.urlopen不喜欢url中的'&'?

更新:感谢Artur的评论,我意识到问题不在于请求本身,而是站点保护机制:js或cookie或网页中的其他内容将一些信息反馈给服务器,以使其能够判断请求是否来自scaper。因此,现在的问题转向如何从网页中获取图片,这比从url下载图片更为复杂。

python-3.x urlopen
1个回答
0
投票

这不是关于&符号,而是关于重定向。尝试添加参数allow_redirects = False来获取,应该没关系

© www.soinside.com 2019 - 2024. All rights reserved.