Search code examples
pythonparsingselenium-webdriverweb-scrapingbots

Click on button with selenium


def get_source_html(url):
    executable_path = "D:\python\Новая папка\chromedriver\chromedriver.exe"
    os.environ["webdriver.chrome.driver"] = executable_path

    chrome_options = Options()
    chrome_options.add_extension('D:\python\Новая папка\CMEAKGJGGJDLCPNCIGGLOBPJBKABHMJL_1_18_47_0.crx')
    #chrome_options.add_experimental_option("detach",True)

    driver = webdriver.Chrome(
        executable_path="D:\python\Новая папка\chromedriver\chromedriver.exe"
    )
    driver = webdriver.Chrome(executable_path=executable_path, chrome_options=chrome_options)
    driver.maximize_window()


    try:
        driver.get(url=url)
        time.sleep(10)
        driver.find_element(By.XPATH, "/html/body/div[1]/div[7]/div[4]/div[1]/div[4]/div[1]/div[3]/div[5]/div[1]/div[1]/div[1]/div[1]/a").click()

when I click on the button nothing happens, I entered its path through xpath. Below is the page code Image. Can you help me with it

I tried to click on button by xpath


Solution

  • I would use an id for the button instead of xpath. The access on elements via xpath is slow and not so stable as an concret html id like:

    <button id="buttonId">
    Click me
    </button>
    

    Then use By.ID instead of By.XPATH:

    driver.find_element(By.ID, "buttonId").click()