python - 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()
谢谢!
解决方案
处理 Selenium 和验证码的简单方法是使用“请求”库并处理 Selenium 和您的请求之间的 cookie。
使用 cookie 将有助于解决您的问题。
推荐阅读
- symfony - Symfony/Doctrine ManyToMany 按分配或保存的顺序获取记录
- r - R : 对名称相似的数据文件进行类似操作
- css - 从水平列表菜单中删除浮动,同时保留下拉菜单
- excel - 为 FIND 函数找到的单元格创建超链接
- swift - 是否可以在 Swift 中创建具有 Self 或关联类型要求的通用计算属性,如果可以,如何?
- sass - 后代选择器 (>) 与根选择器 (&) 结合导致编译错误
- css - 更改其他人网页的小部件大小
- c# - UWP LaunchFullTrustProcessForCurrentAppAsync - 找不到 EXE 文件
- react-native - 将整个屏幕分成四等份
- c++ - 并行写入内存映射文件