Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

未正常運行 #23

Open
jay8651 opened this issue Aug 14, 2024 · 8 comments
Open

未正常運行 #23

jay8651 opened this issue Aug 14, 2024 · 8 comments

Comments

@jay8651
Copy link
Contributor

jay8651 commented Aug 14, 2024

大概在1~3天前我使用舊代碼(以前CloudflareBypassForScraping版本)

import time
from DrissionPage import WebPage

class CloudflareBypasser:
    def __init__(self, page: WebPage):
        self.page = page

    def clickCycle(self):
        if self.page.wait.ele_displayed('.spacer', timeout=1.5):
            time.sleep(1.5)
            self.page.ele(".spacer", timeout=2.5).click()

    def isBypassed(self):
        title = self.page.title.lower()
        return "just a moment" not in title

    def bypass(self):
        while not self.isBypassed():
            time.sleep(1.5)
            print("檢測到驗證頁面。嘗試繞過...")
            time.sleep(1.5)
            self.clickCycle()

有時會打開新分頁導向 https://www.cloudflare.com/products/turnstile/?utm_source=turnstile&utm_campaign=widget

我猜測是點擊到
<a class="cf-link" target="_blank" href="https://www.cloudflare.com/products/turnstile/?utm_source=turnstile&amp;utm_campaign=widget" rel="noopener noreferrer"><svg role="img" aria-label="Cloudflare" id="logo" viewBox="0 0 73 25" fill="none" xmlns="http://www.w3.org/2000/svg">... 後面代碼太多不太重要刪除

大多手動刪除Cookie後,幾個小時內就會正常

現在新舊代碼幾乎無法繞過,猜測是從今天早上或是昨晚
會有兩種狀態
1.畫面不動

image

2.我嘗試使用其他網站,會不斷打開新分頁進入cloudflare網站

@jay8651
Copy link
Contributor Author

jay8651 commented Aug 14, 2024

目前實測下來 https://nopecha.com/demo/cloudflare 可以正常通過
其他網站無法通過 皆是畫面不動沒有任何反應

@sleepyzardo
Copy link

你更新代码了吗

@sleepyzardo
Copy link

对我来说效果很好

@jay8651
Copy link
Contributor Author

jay8651 commented Aug 14, 2024

我成功地根據g1879/DrissionPage#295 修正了代碼
感謝@AnthraX1 提供的方案

主要的改動是將 click() 方法替換為 from DrissionPage.common import Actions 中的 Actions 來模擬用戶交互
這種方法已經在其他網站上進行了測試,效果良好
唯一的例外是一些專門用於測試 Cloudflare 驗證的網站,原因不明

修正後的代碼

import time
from DrissionPage import ChromiumPage
from DrissionPage.common import Actions

class CloudflareBypasser:
    def __init__(self, driver: ChromiumPage, max_retries=-1, log=True):
        self.driver = driver
        self.max_retries = max_retries
        self.log = log
        self.actions = Actions(self.driver)
        
    def log_message(self, message):
        if self.log:
            print(message)

    def click_verification_button(self):
        try:
            if self.driver.wait.ele_displayed('#GBddK6', timeout=1.5):
                self.log_message("Verification button found. Attempting to interact.")
                self.actions.move_to("#GBddK6", duration=0.5).left(120).hold().wait(0.01, 0.15).release()
        except Exception as e:
            self.log_message(f"Error interacting with verification button: {e}")

    def is_bypassed(self):
        try:
            title = self.driver.title.lower()
            return "just a moment" not in title
        except Exception as e:
            self.log_message(f"Error checking page title: {e}")
            return False

    def bypass(self):
        try_count = 0
        while not self.is_bypassed():
            if 0 < self.max_retries + 1 <= try_count:
                self.log_message("Exceeded maximum retries. Bypass failed.")
                break
            self.log_message(f"Attempt {try_count + 1}: Verification page detected. Trying to bypass...")
            self.click_verification_button()
            try_count += 1
            time.sleep(2)
        if self.is_bypassed():
            self.log_message("Bypass successful.")
        else:
            self.log_message("Bypass failed.")

另外@AnthraX1也有提供使用JavaScript注入代碼,讓網站覺得你更像真人
但我對js不熟,也不確定是否是這樣寫代碼,這是我自己的使用方法
使用時機應該是加載驗證網站前使用,這是我自己猜測,以上如有錯誤請告訴我

此外,@AnthraX1 也提供了 JavaScript 代碼,可以通過模擬真實用戶的互動行為來提高繞過 Cloudflare 的成功率
以下是我自己整合的 JavaScript 代碼,主要在載入驗證頁面前注入,以增加繞過驗證的可能性,如果我自己沒理解錯的話

js_code = """
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function modifyClickEvent(event) {
    if (!event._isModified) {
        // Save original values only if not already saved
        event._screenX = event.screenX;
        event._screenY = event.screenY;

        // Define properties only once
        Object.defineProperty(event, 'screenX', {
            get: function() {
                return this._screenX + getRandomInt(0, 200);
            }
        });
        Object.defineProperty(event, 'screenY', {
            get: function() {
                return this._screenY + getRandomInt(0, 200);
            }
        });

        // Mark event as modified
        event._isModified = true;
    }
}

// Store the original addEventListener method
const originalAddEventListener = EventTarget.prototype.addEventListener;

// Override the addEventListener method
EventTarget.prototype.addEventListener = function(type, listener, options) {
    if (type === 'click' || type === 'mousedown' || type === 'mouseup') {
        const wrappedListener = function(event) {
            // Modify the click event properties
            modifyClickEvent(event);

            // Call the original listener with the modified event
            listener.call(this, event);
        };
        // Call the original addEventListener with the wrapped listener
        originalAddEventListener.call(this, type, wrappedListener, options);
    } else {
        // Call the original addEventListener for other event types
        originalAddEventListener.call(this, type, listener, options);
    }
};
"""


# Inject JS code
page.add_init_js(js_code)

@sleepyzardo
Copy link

Create a push request

@sleepyzardo
Copy link

Uhh, doesn't work for some unknown reason

@sleepyzardo
Copy link

Changing The Class back to .spacer fixed it

@sarperavci
Copy link
Owner

My latest commit should solve all problems related to the button location.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants