Open boludoz opened 8 months ago
@nathankurtyka- Вы должны запустить драйвер с '-disable-site-isolation-trials' в этом DOM. Кроме того, вы также неправильно выбрали узел. Это полный скрипт с таким подходом:
import nodriver as uc async def main(): browser_args = ['--disable-web-security','--disable-site-isolation-trials'] browser = await uc.start(browser_args=browser_args) tab = await browser.get("http://www.yescaptcha.cn/auth/login") tab.evaluate("document.querySelector('[title=reCAPTCHA]').contentWindow.document.querySelector('#recaptcha-anchor').click()") await tab.close() if __name__ == "__main__": uc.loop().run_until_complete(main())
JS не нужен, когда использовались браузерные аргументы :)
Hello. I'm fiddling with the fancaptcha, first I need to click on the Next button, which is in the nested iframe, in the third iframe there is this button, I tried everything, I can’t click. Selenium clicks via swith.to.Frame. But I need it through nodriver, since he is not seen as a bot. In the photo, 1 frame is found, 2 and 3 are not, although he sees that there are 3 frames using the selector.
This is the path, but is missing the node that you need to click in the image sent. Get the node and I will share you the full path or just share the web
document.querySelector('#enforcementFrame').contentWindow.document.querySelector('title=\"Verification Challenge\"').contentWindow.document.querySelector('#game-core-frame')
@nathankurtyka- Вы должны запустить драйвер с '-disable-site-isolation-trials' в этом DOM. Кроме того, вы также неправильно отключили узел. Это полный скрипт с таким подходом:
import nodriver as uc async def main(): browser_args = ['--disable-web-security','--disable-site-isolation-trials'] browser = await uc.start(browser_args=browser_args) tab = await browser.get("http://www.yescaptcha.cn/auth/login") tab.evaluate("document.querySelector('[title=reCAPTCHA]').contentWindow.document.querySelector('#recaptcha-anchor').click()") await tab.close() if __name__ == "__main__": uc.loop().run_until_complete(main())
JS не нужен, когда используются браузерные аргументы :)
Здравствуйте. Вожусь с фанкапчей, сначала нужно нажать на кнопку Next, которая во вложенном iframe, в третьем iframe есть эта кнопка, все перепробовал, не могу нажать. Selenium нажимает через swith.to.Frame. А мне нужно через nodriver, так как он не виден как бот. На фото 1 кадр найден, 2 и 3 нет, хотя с помощью селектора видит, что 3 кадра.
Это путь, но отсутствует узел, который вам нужно нажать на отправленном изображении. Получите узел, и я поделюсь с вами полным путем или просто поделюсь веб-сайтом
document.querySelector('#enforcementFrame').contentWindow.document.querySelector('title=\"Verification Challenge\"').contentWindow.document.querySelector('#game-core-frame')
Thanks for the help. Here it is in the picture, and I’ll post it in text if I understand correctly. Path to the button to press //button[@data-theme='home.verifyButton']
I think I figured out your hint. Now another error, js is blocked: description: DOMException: Failed to read a named property 'document' from 'Window': Blocked a frame with origin "https://example.com(There must be an original here)" from accessing a cross-origin frame.
@nathankurtyka- Вы должны запустить драйвер с '-disable-site-isolation-trials' в этом DOM. Кроме того, вы также неправильно отключили узел. Это полный скрипт с таким подходом:
import nodriver as uc async def main(): browser_args = ['--disable-web-security','--disable-site-isolation-trials'] browser = await uc.start(browser_args=browser_args) tab = await browser.get("http://www.yescaptcha.cn/auth/login") tab.evaluate("document.querySelector('[title=reCAPTCHA]').contentWindow.document.querySelector('#recaptcha-anchor').click()") await tab.close() if __name__ == "__main__": uc.loop().run_until_complete(main())
JS не нужен, когда используются браузерные аргументы :)
Здравствуйте. Вожусь с фанкапчей, сначала нужно нажать на кнопку Next, которая во вложенном iframe, в третьем iframe есть эта кнопка, все перепробовал, не могу нажать. Selenium нажимает через swith.to.Frame. А мне нужно через nodriver, так как он не виден как бот. На фото 1 кадр найден, 2 и 3 нет, хотя с помощью селектора видит, что 3 кадра.
Это путь, но отсутствует узел, который вам нужно нажать на отправленном изображении. Получите узел, и я поделюсь с вами полным путем или просто поделюсь веб-сайтом
document.querySelector('#enforcementFrame').contentWindow.document.querySelector('title=\"Verification Challenge\"').contentWindow.document.querySelector('#game-core-frame')
Thanks for the help. Here it is in the picture, and I’ll post it in text if I understand correctly. Path to the button to press //button[@data-theme='home.verifyButton']
iam facing the exact same issue did u found anything?
Failed to read a named property 'document' from 'Window': Blocked a frame with origin "https://example.com(There must be an original here)" from accessing a cross-origin frame
No, I can’t execute js, on test sites the nested iframe is found and clicked, but in my case, there is some kind of protection, it gives an error: Failed to read a named property 'document' from 'Window': Blocked a frame with origin "https://example.com" (There must be an original here)" from accessing a cross-origin frame
I see many are having trouble with JS; otherwise, just do it with nodriver query_selector method. In our example:
import nodriver
async def main():
browser = await nodriver.start(browser_args=['--disable-web-security','--disable-site-isolation-trials'])
tab = await browser.get("http://www.yescaptcha.cn/auth/login")
await tab.sleep(10)
outer_frame = await tab.query_selector('[title=reCAPTCHA]')
form_field = await outer_frame.query_selector('#recaptcha-anchor')
await form_field.click()
asyncio.run(main())
If you have more frames in the tree, just repeat the process until getting the node in the most inner frame. Example:
frame0 = await tab.query_selector(...selector0...)
frame1 = await frame0.query_selector(...selector1...)
frame2 = await frame1.query_selector(...selector2...)
node = await frame2.query_selector(...nodeselector...)
await node.click()
However, the query_selector method not always works with most inner frames. I cannot figure it out why. Javascript always succeeds
Very important 👉query_selector
and select the iframe
He is an expert on this topic, you can contact the guy from Ukraine. He has helped me. @WindBora matches708 @g ail.com
I see many are having trouble with JS; otherwise, just do it with nodriver query_selector method. In our example:
import nodriver async def main(): browser = await nodriver.start(browser_args=['--disable-web-security','--disable-site-isolation-trials']) tab = await browser.get("http://www.yescaptcha.cn/auth/login") await tab.sleep(10) outer_frame = await tab.query_selector('[title=reCAPTCHA]') form_field = await outer_frame.query_selector('#recaptcha-anchor') await form_field.click() asyncio.run(main())
If you have more frames in the tree, just repeat the process until getting the node in the most inner frame. Example:
frame0 = await tab.query_selector(...selector0...) frame1 = await frame0.query_selector(...selector1...) frame2 = await frame1.query_selector(...selector2...) node = await frame2.query_selector(...nodeselector...) await node.click()
However, the query_selector method not always works with most inner frames. I cannot figure it out why. Javascript always succeeds
try with https://github.com/kaliiiiiiiiii/Selenium-Driverless
I see many are having trouble with JS; otherwise, just do it with nodriver query_selector method. In our example:
import nodriver async def main(): browser = await nodriver.start(browser_args=['--disable-web-security','--disable-site-isolation-trials']) tab = await browser.get("http://www.yescaptcha.cn/auth/login") await tab.sleep(10) outer_frame = await tab.query_selector('[title=reCAPTCHA]') form_field = await outer_frame.query_selector('#recaptcha-anchor') await form_field.click() asyncio.run(main())
If you have more frames in the tree, just repeat the process until getting the node in the most inner frame. Example:
frame0 = await tab.query_selector(...selector0...) frame1 = await frame0.query_selector(...selector1...) frame2 = await frame1.query_selector(...selector2...) node = await frame2.query_selector(...nodeselector...) await node.click()
However, the query_selector method not always works with most inner frames. I cannot figure it out why. Javascript always succeeds
try with https://github.com/kaliiiiiiiiii/Selenium-Driverless
This project hasn't been updated for a long time, can it still be used normally now?
I see many are having trouble with JS; otherwise, just do it with nodriver query_selector method. In our example:
import nodriver async def main(): browser = await nodriver.start(browser_args=['--disable-web-security','--disable-site-isolation-trials']) tab = await browser.get("http://www.yescaptcha.cn/auth/login") await tab.sleep(10) outer_frame = await tab.query_selector('[title=reCAPTCHA]') form_field = await outer_frame.query_selector('#recaptcha-anchor') await form_field.click() asyncio.run(main())
If you have more frames in the tree, just repeat the process until getting the node in the most inner frame. Example:
frame0 = await tab.query_selector(...selector0...) frame1 = await frame0.query_selector(...selector1...) frame2 = await frame1.query_selector(...selector2...) node = await frame2.query_selector(...nodeselector...) await node.click()
However, the query_selector method not always works with most inner frames. I cannot figure it out why. Javascript always succeeds
try with https://github.com/kaliiiiiiiiii/Selenium-Driverless
This project hasn't been updated for a long time, can it still be used normally now?
just run in expert mode command and use this, must use selectors
usually we don't need access to inside iframe I'll show how it works for me:
import nodriver as uc
class Registrator:
...
@staticmethod
async def get_hcaptcha_response(url: str, proxy_url: str | None = None):
config = uc.Config()
if proxy_url:
config.add_argument("--proxy-server={proxy_url}")
driver = await uc.start(config)
page = await driver.get(url)
iframe = await page.select("iframe[src^='https://newassets.hcaptcha.com/captcha/v1/']")
await iframe.scroll_into_view()
await page.sleep(4)
await iframe.mouse_click()
hcaptcha = await page.wait_for("iframe[data-hcaptcha-response]:not([data-hcaptcha-response=''])", timeout=300)
driver.stop()
return hcaptcha["data-hcaptcha-response"]
@staticmethod
async def get_recaptcha_response(url: str, proxy_url: str | None = None):
config = uc.Config()
if proxy_url:
config.add_argument(f"--proxy-server={proxy_url}")
driver = await uc.start(config)
page = await driver.get(url)
iframe = await page.select("iframe[src^='https://www.google.com/recaptcha/api2/anchor?']", 30)
await iframe.scroll_into_view()
await page.sleep(4)
await iframe.mouse_click()
recaptcha = await page.select("#g-recaptcha-response")
recaptcha_response = None
async with asyncio.timeout(300):
while not recaptcha_response:
#recaptcha.value nor recaptcha.attrs["value"] doesn't work here, recaptcha.update() didn't help
recaptcha_response = await recaptcha.apply("(elem) => {return elem.value}")
await page.sleep(1)
driver.stop()
return recaptcha_response
I'm having problems interacting with an element in a geo captcha's iframe. Can you help me?
from nodriver import * import asyncio import time import os
from nodriver import * from nodriver.cdp import page import json import asyncio import base64 import os import time
async def get_captcha_data(tab): try: print("Đang tìm frame captcha...")
# Đợi và tìm iframe
iframe = await tab.select("iframe[src*='captcha-delivery.com']")
if not iframe:
print("Không tìm thấy iframe captcha")
return False
print("Đã tìm thấy iframe, scroll vào view...")
await iframe.scroll_into_view()
await asyncio.sleep(2)
# Script lấy ảnh
js_get_canvas = """() => {
const canvases = document.querySelectorAll('#captcha__puzzle canvas');
if (!canvases || canvases.length === 0) return null;
const images = [];
for (const canvas of canvases) {
try {
images.push(canvas.toDataURL('image/png'));
} catch(e) {
console.error('Lỗi canvas:', e);
}
}
return images;
}"""
# Thực thi script trong iframe để lấy ảnh
images = await tab.evaluate(js_get_canvas, iframe_selector="iframe[src*='captcha-delivery.com']")
if not images:
print("Không lấy được ảnh captcha")
return False
print(f"Đã tìm thấy {len(images)} ảnh")
# Lưu ảnh
os.makedirs('captcha_images', exist_ok=True)
timestamp = time.strftime("%Y%m%d_%H%M%S")
for idx, img_data in enumerate(images):
try:
img_binary = base64.b64decode(img_data.split(',')[1])
filename = f'captcha_images/captcha_{timestamp}_{idx}.png'
with open(filename, 'wb') as f:
f.write(img_binary)
print(f"Đã lưu ảnh: {filename}")
except Exception as e:
print(f"Lỗi khi lưu ảnh {idx}: {e}")
return True
except Exception as e:
print(f"Lỗi xử lý captcha: {e}")
import traceback
traceback.print_exc()
return False
async def main(): try:
username = "JEPJGIHI3NIYR"
current_password = "i8n4lQQ@UnQI"
new_password = "i8n4lQQ@UnQI"
# Đường dẫn extension
extension_path = r"C:\Users\bossb\Downloads\MAYTINH\ExtensionGetUrlCaptcha"
# Cookie string
cookie_str = "_ga=GA1.1.520467708.1730728477; sso_key=48e89b676dcd9b6ffb07b023e2c2530c7a97f4db4209bec04aade4825a79419f; _ga_1M7M9L6VPX=GS1.1.1730728477.1.0.1730728489.0.0.0; datadome=jLRzg2HsytRxcyzcIWcMw4slC0Zp1r2BU8WhAt_yB2PkR2_MCN0mnDqUhO2tUOu39GsIiSqVPo2mGLELkurM23NxaFwBFlCasXUvWT72x2_4UEFptW8Uvtn0fn6K~rLr; ac_session=jt3t2c3xf59knho35eltmmjtnh9u7cqy"
# Thiết lập tham số trình duyệt với cookie
browser_arguments = [
# '--no-sandbox',
# '--disable-gpu',
# '--disable-dev-shm-usage',
# '--disable-blink-features=AutomationControlled',
# f'--load-extension={extension_path}',
f'--cookie-server=account.garena.com',
f'--cookie-value={cookie_str}'
]
# Khởi tạo trình duyệt
browser = await start(
headless=False,
browser_args=browser_arguments,
lang="en-US"
)
# Mở trang web
tab = await browser.get('https://account.garena.com/')
await asyncio.sleep(1)
# Sau khi trang load xong, thực hiện các thao tác JavaScript để set cookie
js_cookie = f'''
function setCookie(name, value) {{
document.cookie = name + "=" + value + "; path=/; domain=.garena.com";
}}
const cookies = "{cookie_str}".split(';');
for(let cookie of cookies) {{
const [name, value] = cookie.trim().split('=');
if(name && value) {{
setCookie(name, value);
}}
}}
'''
await tab.evaluate(js_cookie)
await asyncio.sleep(2)
# Refresh trang để áp dụng cookies
await tab.reload()
security_button = await tab.find("Bảo mật", best_match=True)
await security_button.click()
# await asyncio.sleep(1)
password_change = await tab.query_selector('#main > div > div.wrapper > div.main > aside > div > a:nth-child(2) > div')
await password_change.click()
await asyncio.sleep(1)
# Fill password change form...
current_pwd = await tab.query_selector('#J-form-curpwd')
await current_pwd.send_keys(current_password)
new_pwd = await tab.query_selector('#J-form-newpwd')
await new_pwd.click()
await new_pwd.send_keys(new_password)
confirm_pwd = await tab.query_selector('input[placeholder="Xác nhận Mật khẩu mới"]')
await confirm_pwd.click()
await confirm_pwd.send_keys(new_password)
submit = await tab.query_selector('input.content__submit[type="submit"]')
await submit.click()
await asyncio.sleep(5)
await get_captcha_data(tab)
await asyncio.sleep(5444)
except Exception as e:
print(f"Lỗi chi tiết:", str(e))
if name == "main": asyncio.run(main())
I'm having difficulty selecting an iframe and using click inside it, I'm using the find and click functions but they don't work inside the iframe. How do I select it?
I really think that nodriver is worth it and I am not going to get off the boat because of this simple obstacle.
My question is, how can I access an iframe within a website?