如何使用Python从CAPTCHA下载图像?

问题描述 投票:0回答:2

我需要在此登录站点中下载定制的验证码中的图像。我该怎么办:(?

This is the login site, there are five images

这是链接:https://portalempresas.sb.cl/login.php

我一直在尝试使用此代码,而另一个用户(@EnriqueBet)帮助我:

from io import BytesIO
from PIL import Image

# Download image function
def downloadImage(element,imgName):
    img = element.screenshot_as_png
    stream = BytesIO(img)
    image = Image.open(stream).convert("RGB")
    image.save(imgName)

# Find all the web elements of the captcha images    
image_elements = driver.find_elements_by_xpath("/html/body/div[1]/div/div/section/div[1]/div[3]/div/div/div[2]/div[*]")

# Output name for the images
image_base_name = "Imagen_[idx].png"

# Download each image
for i in range(len(image_elements)):
    downloadImage(image_elements[i],image_base_name.replace("[idx]","%s"%i)

但是,当它尝试获取所有图像元素时

image_elements = driver.find_elements_by_xpath("/html/body/div[1]/div/div/section/div[1]/div[3]/div/div/div[2]/div[*]")

它失败了,什么也没得到。请帮忙! :(

python python-imaging-library
2个回答
0
投票

不是定义图像的显式路径,而是为什么不简单下载页面上存在的所有图像。这将起作用,因为页面本身只有5张图像,并且您要下载所有图像。请参阅下面的方法。

以下内容应从给定页面提取所有图像并将其写入运行脚本的目录。

import re
import requests
from bs4 import BeautifulSoup

site = ''#set image url here
response = requests.get(site)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')

urls = [img['src'] for img in img_tags]

for url in urls:
    filename = re.search(r'/([\w_-]+[.](jpg|gif|png))$', url)
    with open(filename.group(1), 'wb') as f:
        if 'http' not in url:
            # sometimes an image source can be relative 
            # if it is provide the base url which also happens 
            # to be the site variable atm. 
            url = '{}{}'.format(site, url)
        response = requests.get(url)
        f.write(response.content)

该代码取自here,贷方归其各自所有者。


0
投票

这是我先前的帖子的后续回答

由于硒和浏览器上的版本控制问题,我无法成功运行硒。

尽管我想到了另一种下载和提取验证码上显示的所有图像的方法。如您所知,图像在每次访问时都会发生变化,因此要收集所有图像,最好的选择是使它们自动化,而不是从站点手动保存图像。

要使其自动化,请执行以下步骤。

[首先,使用硒导航到该站点并拍摄该站点的屏幕快照。例如,

from selenium import webdriver

DRIVER = 'chromedriver'
driver = webdriver.Chrome(DRIVER)
driver.get('https://www.spotify.com')
screenshot = driver.save_screenshot('my_screenshot.png')
driver.quit()

这会将其保存在本地。然后,您可以使用pil之类的库打开图像并裁剪验证码的图像。

这将像这样完成

im = Image.open('0.png').convert('L')
im = im.crop((1, 1, 98, 33))
im.save('my_screenshot.png)

希望您在这里有了这个主意。您需要对所有图像一个接一个地完成此操作,最好在for循环中适当更改作物尺寸。

© www.soinside.com 2019 - 2024. All rights reserved.