简体   繁体   中英

How to Click “Accept Cookies” on a page without an ID or Name with Python Selenium

i am trying to figure out how to click a button called "Alles akzeptieren" to accept the cookies of the website. On other websites I used an ID or a name where it worked. But on this website I can't get access to the button and click it. The HTML looks like this:

<button tabindex="0" title="Alle akzeptieren" aria-label="Alle akzeptieren" class="message-component message-button no-children button-responsive-primary" path="[0,1,1,0]" style="padding: 5px 0px; margin: 0px; border-width: 1px; border-color: rgb(50, 100, 255); border-radius: 4px; border-style: solid; font-size: 14px; font-weight: 500; color: rgb(255, 255, 255); font-family: verdana, geneva, sans-serif; width: calc(100% - 0px); background: rgb(50, 100, 255);">Alle akzeptieren</button>

The Xpath is: /html/body/div/div[2]/div[3]/div[2]/button

I tried the following code:

#accept cookies
time.sleep(5)
AcceptCookies = driver.find_element_by_link_text_name("Alles Akzeptieren")
AcceptCookies.click

Or

#accept cookies
time.sleep(5)
AcceptCookies = driver.find_element_by_class_name("message-component message-button no-children button-responsive-primary")
AcceptCookies.click

Does somebody know what the problem is? When I use this code I get the Error:

NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".message-component message-button no-children button-responsive-primary"}
  (Session info: chrome=89.0.4389.90)

Or

AttributeError: 'WebDriver' object has no attribute 'find_element_by_link_text_name'

there is no href attribute in your button so find_element_by_link_text will not work you can use xpath

Try with this css locator:

AcceptCookies = driver.find_element_by_css_selector("button[title='Alle akzeptieren']")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM