繁体   English   中英

使用python抓取图像但找不到图像

[英]webscraping an image with python but can't find image

我正在尝试从URL刮取stockcharts.com上的图表图像。 例如,来自: http : //stockcharts.com/h-sc/ui?s=AMZN

但是,当检查有问题的元素时,它不是带有.jpg,.png等后缀的正确图像src。 例如,上述链接中的相关元素为: http : //stockcharts.com/c-sc/sc?s=AMZN&p=D&b=5&g=0&i=0&r=1479451634864

因此,当我尝试在python 2.7中使用以下代码时,在共享脚本的目录中得到一个空文件:

import urllib
url = "http://stockcharts.com/c-sc/sc?s=AMZN&p=D&b=5&g=0&i=0&r=1479451634864"
filename = "testimg.jpg"
urllib.urlretrieve(url, filename)

这是JavaScript呈现的页面,还是我缺少什么? 引用其他地方?

该站点检查User-Agent标头; 它仅允许特定的用户代理。

您需要更改标题以获取图像。 否则,站点将返回403禁止响应。

urllib.urlretrieve不接受其他标头,您需要使用urllib2.urlopen / urllib2.Request指定自定义标头并自己保存文件:

import urllib2

url = "http://stockcharts.com/c-sc/sc?s=AMZN&p=D&b=5&g=0&i=0&r=1479451634864"
filename = "sc.png"
req = urllib2.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
u = urllib2.urlopen(req)
with open(filename, 'wb') as f:
    f.write(u.read())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM