簡體   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