首页 > 解决方案 > Python、Selenium 和 2Captcha 解决验证码不起作用

问题描述

我正在尝试使用 2Captcha 来解决 recaptcha v2。当我运行我的代码时,它成功获取recaptcha结果并将其存储在result ['code']中,但是当我执行以下代码提交时,页面似乎只刷新并且recaptcha没有得到解决。请原谅我的错误,我对编码非常陌生,因此我的代码非常粗糙和实验性。我可以在https://2captcha.com/demo/recaptcha-v2?level=high使用稍微修改的代码来解决验证码,但无法让它为我的目的工作。谁能向我解释我可以做些什么不同的事情?

driver.find_element_by_id("g-recaptcha-response").submit()

我也在下面包含了我的完整代码

from selenium import webdriver
import time
import json
import sys
import os
from twocaptcha import TwoCaptcha


loginInfo = json.load(open('logn.json'))
username = loginInfo['username']
password = loginInfo['password']


driver = webdriver.Firefox()
driver.get("https://www.gaiaonline.com/")

loginButton = driver.find_element_by_xpath('//*[@id="login"]')
loginButton.click()

time.sleep(1)

usernameField = driver.find_element_by_xpath('//*[@id="username"]')
usernameField.send_keys(username)

passwordField = driver.find_element_by_xpath('//*[@id="password"]')
passwordField.send_keys(password)

rememberMe = driver.find_element_by_xpath('//*[@id="autologin"]')
rememberMe.click()

loginButton2 = driver.find_element_by_xpath('//*[@id="signInButton"]')
loginButton2.click()

time.sleep(5)

driver.get("https://www.gaiaonline.com/forum/compose/entry/new/79469475/")
time.sleep(4)

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
api_key = os.getenv('APIKEY_2CAPTCHA', 'My_API_KEY')

solver = TwoCaptcha(api_key)

result = solver.recaptcha(sitekey=driver.find_element_by_class_name("g-recaptcha").get_attribute("data-sitekey"),
        url=driver.current_url)

print(result['code'])


driver.execute_script('var element=document.getElementById("g-recaptcha-response"); element.style.display="";')
driver.execute_script("""
  document.getElementById("g-recaptcha-response").innerHTML = arguments[0]
""", result['code'])
time.sleep(3)
driver.find_element_by_id("g-recaptcha-response").submit()

谢谢!

标签: pythonseleniumselenium-webdriver2captcha

解决方案


处理 Selenium 和验证码的简单方法是使用“请求”库并处理 Selenium 和您的请求之间的 cookie。

使用 cookie 将有助于解决您的问题。


推荐阅读