Home  >  Q&A  >  body text

python selenium gets image verification code

I want to cache the image verification code locally, and then let the user see the image through the web service and manually type the code to log in.
Considering that the official operation is interface-less, selenium screenshots cannot be used.
In addition to selenium screenshot and right-click method, is there any other way?

Currently I think of using js to re-request the verification code into canvas and then toDataURL into png base64 code and output it to Dom and then use selenium to obtain it.
The following code test uses the login entrance verification code of the mobile mall.

$('body').append('<canvas id="CAVASIMG"></canvas>');
var img=new Image();
img.src="http://shop.10086.cn/i/authImg";
var d=document.getElementById("CAVASIMG");
var cxt=d.getContext("2d");
img.onload = function(){
    d.width = img.width;d.height = img.height;
    cxt.drawImage(img,0,0);
    console.log(d.toDataURL('png'));
};

If the URL requesting the verification code is from a different domain than the login URL, a cross-domain error will be reported.
You also need to test whether the verification code image obtained in this way still exists within the validity period of the current session.
How to solve the above cross-domain problem?

PHP中文网PHP中文网2685 days ago1566

reply all(4)I'll reply

  • 欧阳克

    欧阳克2017-06-12 09:23:28

    You first need to capture the packet to see the request path of the image, and then use requests to download the image

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-12 09:23:28

    The method above is a method, you can also use selenium + PhantomJS

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-12 09:23:28

    The picture verification code and the cookies when reading the picture are integrated

    Just make sure the verification code you answer is consistent with the cookies.

    reply
    0
  • 高洛峰

    高洛峰2017-06-12 09:23:28

    In the end I used the js method

    var img=document.getElementById('IMGCODEID');
    var d=document.createElement('CANVAS');
    var cxt=d.getContext('2d');
    d.width=img.width;d.height=img.height;
    cxt.drawImage(img,0,0);
    img.src=d.toDataURL('png');

    reply
    0
  • Cancelreply