Python: Issue injecting javascript in new page of the same window

I would like to capture the names,id,…etc of clicked controls (input text, button,..etc) of a page (facebook.com for example). For that I am injecting a script to the page code using selenium (see code below). Everything works fine for the first open page. However, when I move to a new page by clicking on a link (for example: Create a Page: https://www.facebook.com/pages/create/?ref_type=registration_form) the script is not injected into the new open page. The code is below:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from selenium import webdriver
# Initialize the Firefox WebDriver
driver = webdriver.Firefox()
# Open the webpage
url = "https://www.facebook.com" # Replace with the URL of the webpage you want to interact with
driver.get(url)
# JavaScript code to inject
js_code = """
document.addEventListener('click', function(event) {
var target = event.target;
// Function to generate CSS selector for the element
function getCssSelector(el) {
if (!(el instanceof Element)) return;
var path = [];
while (el.nodeType === Node.ELEMENT_NODE) {
var selector = el.nodeName.toLowerCase();
if (el.id) {
selector += '#' + el.id;
path.unshift(selector);
break;
} else {
var sib = el, nth = 1;
while (sib = el.previousElementSibling) {
if (sib.nodeName.toLowerCase() == selector)
nth++;
}
if (nth != 1)
selector += ":nth-of-type("+nth+")";
}
path.unshift(selector);
el = el.parentNode;
}
return path.join(" > ");
}
// Function to extract href attribute value from the clicked link
function getHref(el) {
if (!(el instanceof HTMLAnchorElement)) return;
return el.href;
}
// Generate CSS selector for the clicked element
var cssSelector = getCssSelector(target);
// If the clicked element is a link, extract the href attribute value
var href = getHref(target);
// Print information about the clicked element
var elementInfo = {
tagName: target.tagName,
id: target.id,
className: target.className,
type: target.type,
cssSelector: cssSelector,
href: href
};
console.log('Clicked Element:', elementInfo);
alert(JSON.stringify(elementInfo));
});
"""
# Function to inject the click listener JavaScript code
def inject_click_listener_script():
driver.execute_script(js_code)
# Inject the click listener script on the initial page
inject_click_listener_script()
# Wait for user interactions
print("Please click on any element on the webpage. Press Enter when done...")
input()
# Function to wait for the page to finish loading and inject the script again
def wait_and_inject_script():
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
inject_click_listener_script()
# Monitor for page changes within the same window
while True:
# Check if the user wants to exit
exit_command = input("Press Enter to continue, or type 'exit' to quit: ")
if exit_command.lower() == "exit":
break
# Execute the script on the new page
wait_and_inject_script()
# Quit the driver
driver.quit()
</code>
<code>from selenium import webdriver # Initialize the Firefox WebDriver driver = webdriver.Firefox() # Open the webpage url = "https://www.facebook.com" # Replace with the URL of the webpage you want to interact with driver.get(url) # JavaScript code to inject js_code = """ document.addEventListener('click', function(event) { var target = event.target; // Function to generate CSS selector for the element function getCssSelector(el) { if (!(el instanceof Element)) return; var path = []; while (el.nodeType === Node.ELEMENT_NODE) { var selector = el.nodeName.toLowerCase(); if (el.id) { selector += '#' + el.id; path.unshift(selector); break; } else { var sib = el, nth = 1; while (sib = el.previousElementSibling) { if (sib.nodeName.toLowerCase() == selector) nth++; } if (nth != 1) selector += ":nth-of-type("+nth+")"; } path.unshift(selector); el = el.parentNode; } return path.join(" > "); } // Function to extract href attribute value from the clicked link function getHref(el) { if (!(el instanceof HTMLAnchorElement)) return; return el.href; } // Generate CSS selector for the clicked element var cssSelector = getCssSelector(target); // If the clicked element is a link, extract the href attribute value var href = getHref(target); // Print information about the clicked element var elementInfo = { tagName: target.tagName, id: target.id, className: target.className, type: target.type, cssSelector: cssSelector, href: href }; console.log('Clicked Element:', elementInfo); alert(JSON.stringify(elementInfo)); }); """ # Function to inject the click listener JavaScript code def inject_click_listener_script(): driver.execute_script(js_code) # Inject the click listener script on the initial page inject_click_listener_script() # Wait for user interactions print("Please click on any element on the webpage. Press Enter when done...") input() # Function to wait for the page to finish loading and inject the script again def wait_and_inject_script(): WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body"))) inject_click_listener_script() # Monitor for page changes within the same window while True: # Check if the user wants to exit exit_command = input("Press Enter to continue, or type 'exit' to quit: ") if exit_command.lower() == "exit": break # Execute the script on the new page wait_and_inject_script() # Quit the driver driver.quit() </code>
from selenium import webdriver

# Initialize the Firefox WebDriver
driver = webdriver.Firefox()

# Open the webpage
url = "https://www.facebook.com"  # Replace with the URL of the webpage you want to interact with
driver.get(url)

# JavaScript code to inject
js_code = """
document.addEventListener('click', function(event) {
    var target = event.target;
    // Function to generate CSS selector for the element
    function getCssSelector(el) {
        if (!(el instanceof Element)) return;
        var path = [];
        while (el.nodeType === Node.ELEMENT_NODE) {
            var selector = el.nodeName.toLowerCase();
            if (el.id) {
                selector += '#' + el.id;
                path.unshift(selector);
                break;
            } else {
                var sib = el, nth = 1;
                while (sib = el.previousElementSibling) {
                    if (sib.nodeName.toLowerCase() == selector)
                        nth++;
                }
                if (nth != 1)
                    selector += ":nth-of-type("+nth+")";
            }
            path.unshift(selector);
            el = el.parentNode;
        }
        return path.join(" > ");
    }

    // Function to extract href attribute value from the clicked link
    function getHref(el) {
        if (!(el instanceof HTMLAnchorElement)) return;
        return el.href;
    }

    // Generate CSS selector for the clicked element
    var cssSelector = getCssSelector(target);

    // If the clicked element is a link, extract the href attribute value
    var href = getHref(target);

    // Print information about the clicked element
    var elementInfo = {
        tagName: target.tagName,
        id: target.id,
        className: target.className,
        type: target.type,
        cssSelector: cssSelector,
        href: href
    };
    console.log('Clicked Element:', elementInfo);
    alert(JSON.stringify(elementInfo));
});
"""

# Function to inject the click listener JavaScript code
def inject_click_listener_script():
    driver.execute_script(js_code)

# Inject the click listener script on the initial page
inject_click_listener_script()

# Wait for user interactions
print("Please click on any element on the webpage. Press Enter when done...")
input()

# Function to wait for the page to finish loading and inject the script again
def wait_and_inject_script():
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
    inject_click_listener_script()

# Monitor for page changes within the same window
while True:
    # Check if the user wants to exit
    exit_command = input("Press Enter to continue, or type 'exit' to quit: ")
    if exit_command.lower() == "exit":
        break

    # Execute the script on the new page
    wait_and_inject_script()

# Quit the driver
driver.quit()

it seems that the condition WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
is never meet.
Any advice or help is appreciated.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật