Skip to main content
 首页 » 编程设计

python之如何使用python从linkedin下载图片

2025年05月04日8wayfarer

我正在尝试使用 python 中的 urllib 下载公司 Logo 。但是每张图片的 src 都是一个链接,它不以 .jpg 或 .jpeg 或任何其他图像文件格式结尾,例如:https://media.licdn.com/dms/image/C4E0BAQFV8hEDyrhygA/company-logo_100_100/0?e=1584576000&v=beta&t=rCeGYSP-rfRqEnSRiZszB3F1Bcks7kyXTYoiGrqUPTg。 我为此使用以下代码:

imageSrc = companySoup.find('img', {'class': 'org-top-card-primary-content__logo Elevation-0dp lazy-image loaded ember-view'}) 
        imageSrcUrl = imageSrc['src'].strip() 
        print(imageSrcUrl) 
        urllib.urlretrieve(imageSrcUrl, os.path.basename(imageSrcUrl)) 

请帮助我如何在 python 中下载它。

请您参考如下方法:

这是我在pygame中使用的。但是您可以修改它以根据需要处理图像(例如 PIL?)

import requests 
import io 
import pygame 
import traceback 
 
def loadURLImage(url, headers='', timeout=10): 
 
    image = None 
 
    try: 
        with requests.get(url, headers=headers, timeout=timeout) as pic: 
            image_str = pic.content 
            image_file = io.BytesIO(image_str) 
            # Use .convert_alpha() if you find troubles with transparency 
            image = pygame.image.load(image_file) 
    except: 
        print("Error getting image from URL", url) 
        print(traceback.format_exc()) 
 
    return image 

现在您可以将其保存到磁盘(作为 BMP、TGA、PNG 或 JPEG),使用:

file_name = "test.jpeg"     
pygame.image.save(image, file_name)