Seleniumでキャプチャ画像をダウンロードしようとしていますが、ブラウザに表示されているものとは異なる画像がダウンロードされます。ブラウザを変更せずにもう一度画像をダウンロードしようとすると、別の画像が表示されます。
何かご意見は?
from selenium import webdriver
import urllib
driver = webdriver.Firefox()
driver.get("http://sistemas.cvm.gov.br/?fundosreg")
# Change frame.
driver.switch_to.frame("Main")
# Download image/captcha.
img = driver.find_element_by_xpath(".//*[@id='trRandom3']/td[2]/img")
src = img.get_attribute('src')
urllib.request.urlretrieve(src, "captcha.jpeg")
画像のリンクを開くとsrc
、ランダムに新しいキャプチャ画像が表示されるためです。
画像からファイルをダウンロードする代わりにsrc
、スクリーンショットを撮ってブラウザに表示することができます。ただし、Pillow
(pip install Pillow
)をダウンロードして、この回答に記載されている方法で使用する必要があります。
from PIL import Image
from selenium import webdriver
def get_captcha(driver, element, path):
# now that we have the preliminary stuff out of the way time to get that image :D
location = element.location
size = element.size
# saves screenshot of entire page
driver.save_screenshot(path)
# uses PIL library to open image in memory
image = Image.open(path)
left = location['x']
top = location['y'] + 140
right = location['x'] + size['width']
bottom = location['y'] + size['height'] + 140
image = image.crop((left, top, right, bottom)) # defines crop points
image.save(path, 'jpeg') # saves new cropped image
driver = webdriver.Firefox()
driver.get("http://sistemas.cvm.gov.br/?fundosreg")
# change frame
driver.switch_to.frame("Main")
# download image/captcha
img = driver.find_element_by_xpath(".//*[@id='trRandom3']/td[2]/img")
get_captcha(driver, img, "captcha.jpeg")
driver = webdriver.Firefox()
driver.get("http://sistemas.cvm.gov.br/?fundosreg")
# change frame
driver.switch_to.frame("Main")
# download image/captcha
img = driver.find_element_by_xpath(".//*[@id='trRandom3']/td[2]/img")
get_captcha(driver, img, "captcha.jpeg")
(あなたの場合に機能するように、コードを少し変更したことに注意してください。)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加