0

I want to capture captcha code with python and selenium. So far I have this:

elem = driver.find_element_by_css_selector("#imagecpt")
loc, size  = elem.location, elem.size
left, top     = loc['x'], (loc['y'] - 587)
width, height = size['width'], size['height']
box = (int(left), int(top), int(left+width), int(top+height))
screenshot = driver.get_screenshot_as_base64()
img = Image.open(StringIO.StringIO(base64.b64decode(screenshot)))
captcha = img.crop(box)
captcha.save('captcha.png', 'PNG')

The code is working but there is a small problem, the top position returned by elem.location is complete position in website.

To capture the captcha code in my website I need to scroll down the page, as Selenium takes screenshot only for the visible part of the website and the top size returned by elem.location is not valid.

To solve the scrolling problem I am using a hardcoded value - 587. How can I rewrite the code without this hardcoded value?

1 Answer 1

2

Use ActionChains.move_to_element() method to scroll to the captcha.

Also, take a look at the location_once_scrolled_into_view in the Selenium documentation as it may be helpful.

THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can click it. This method should cause the element to be scrolled into view.

Returns the top lefthand corner location on the screen, or None if the element is not visible.

from selenium.webdriver import ActionChains

elem = driver.find_element_by_css_selector("#imagecpt")

action_chain = ActionChains(driver)
action_chain.move_to_element(elem)
action_chain.perform()

loc, size = elem.location_once_scrolled_into_view, elem.size
left, top = loc['x'], loc['y']

width, height = size['width'], size['height']
box = (int(left), int(top), int(left + width), int(top + height))

screenshot = driver.get_screenshot_as_base64()
img = Image.open(StringIO.StringIO(base64.b64decode(screenshot)))

captcha = img.crop(box)
captcha.save('captcha.png', 'PNG')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.