首页 > 解决方案 > 如何使用 Selenium Python 下载具有“数据:图像”类型源的图像

问题描述

我尝试以正常方式执行此操作,通过 ID 选择图像,然后获取src属性的内容,如下所示:

img = wd.find_element_by_id('image')
src = img.get_attribute('src')
urllib.request.urlretrieve(src, "local_image.png")

但是,此代码段的第三行按预期失败a string or bytes-like object

完整追溯:

Traceback (most recent call last):
  File "image.py", line 36, in <module>
    urllib.request.urlretrieve(src, "image.png")
  File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\urllib\request.py", line 245, in urlretrieve
    url_type, path = _splittype(url)
  File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\urllib\parse.py", line 1008, in _splittype
    match = _typeprog.match(url)
TypeError: expected string or bytes-like object

有没有人有任何指示?

标签: pythonseleniumweb-scraping

解决方案


requests您可以使用和shutil模块完成它:

import shutil
import requests
img = wd.find_elements_by_tag_name('img')
src = img.get_attribute('src')
print(src)
url = 'yoururl/'+ src['my_image']
response = requests.get(url, stream=True)
with open('my_pic.png', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file

推荐阅读