使用Python从encryptedtbn0.gstatic.com下载图像

2024-06-28 15:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从谷歌抓取图片。我的脚本中有图像链接,但这个有这种格式

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQh6rPd9hx_fUGzorshx1fG5kzUM5FGCSYmm2YBuLU3uSFFI5BviIWd6hrHbw&s

我打开了,这是图像,但我不能使用urllib.urlretrieve(imagenurl,imagen)进行下载

有人知道其他下载方式吗? 我正在使用python 2.7

import requests
from  bs4 import BeautifulSoup
import urllib

def run():
    palabra ='pez'
    response = requests.get('https://www.google.com/search?q={}&hl=es&sxsrf=ALeKk00KoMQKffGLNWV5UEKbuPwpySPuig:1596391733831&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiajd7Rjv3qAhXqTN8KHSINBkcQ_AUoAXoECBoQAw&biw=1262&bih=593'.format(palabra))
    soup = BeautifulSoup(response.content,'html.parser')
    imagenes = soup.find_all('img')

    for i in range(1,5):
        imagen_i = imagenes[i]['src']
        imagen = imagen_i.split('/')[-1]
        print(imagen_i)
        #urllib.urlretrieve(imagen_i)


if __name__ == '__main__':
    run()


Tags: runhttps图像importcomresponse图片urllib
1条回答
网友
1楼 · 发布于 2024-06-28 15:20:40

我可以在Linux上用urlretrieve下载它,但是您应该检查print(imagen)以查看您使用的文件名

它的名字像

images?q=tbn:ANd9GcQh6rPd9hx_fUGzorshx1fG5kzUM5FGCSYmm2YBuLU3uSFFI5BviIWd6hrHbw&s 

使用系统中可能不允许的字符-因此它可能不会保存它-您应该手动创建文件名-即1.jpg2.jpg"{}.jpg".format(i)-或者您应该从文件名中删除不允许的字符


import requests
from  bs4 import BeautifulSoup
import urllib

palabra ='pez'

response = requests.get('https://www.google.com/search?q={}&hl=es&sxsrf=ALeKk00KoMQKffGLNWV5UEKbuPwpySPuig:1596391733831&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiajd7Rjv3qAhXqTN8KHSINBkcQ_AUoAXoECBoQAw&biw=1262&bih=593'.format(palabra))
soup = BeautifulSoup(response.content,'html.parser')
all_images = soup.find_all('img')

for i, img in enumerate(all_images[1:5], 1):
    src = img['src']
    print 'src:', src
    
    filename = src.split('/')[-1]
    print 'filename:', filename

    #import urlparse
    #parts = urlparse.urlparse(src)
    #query = urlparse.parse_qs(parts.query)
    #q = query['q'][0]
    #filename = q.split(':')[1]
    #print 'filename:', filename
            
    filename = '{}.jpg'.format(i)
    print 'filename:', filename
    
    urllib.urlretrieve(src, filename)

相关问题 更多 >