#python #selenium #selenium-chromedriver
Вопрос:
Я использую этот веб-сайт: https://www.marketscreener.com/stock-exchange/calendar/finance/
Я добавил различные аргументы и экспериментальные опции для отключения всплывающих окон, но всплывающее окно, которое вы увидите, продолжает появляться.
Я пытаюсь закрыть его, нажав большую зеленую кнопку «Принять и закрыть», но ошибка говорит о том, что такого элемента не существует
код:
url='https://www.marketscreener.com/stock-exchange/calendar/finance/'
logger.info('loading:',url)
options=webdriver.ChromeOptions()
chrome_prefs = {}
options.experimental_options["prefs"]=chrome_prefs
options.add_experimental_option("excludeSwitches",['disable-popup-blocking'])
chrome_prefs["profile.default_content_settings"] = {"popups":1}
options.add_argument('--disable-browser-side-navigation')
options.add_argument('--disable-infobars')
options.add_argument('--disable-extensions')
options.add_argument('--disable-popup-blocking')
options.add_argument('--disable-notifications')
driver = webdriver.Chrome(executable_path=r'\foo',options=options)
driver.get(url)
driver.find_element_by_xpath("//button[@title='Accept amp; Close']").click()
древовидная структура:
<div class="message-component message-row" style="padding: 3px 5px;
margin: 5px 10px; border-width: 0px; border-color: rgb(0, 0, 0); border-
radius: 0px; border-style: solid; width: calc(100% - 30px); height:
auto; justify-content: flex-start; align-items: center; flex-direction:
column;"><button title="Accept amp;amp; Close" class="message-component
message-button no-children focusable primary accept customizable
sp_choice_type_11" style="padding: 10px 0px; margin: 0px 5px; border-
width: 0px; border-color: rgb(0, 0, 0); border-radius: 5px; border-
style: solid; font-size: 16px; font-weight: 800; color: rgb(255, 255,
255); font-family: arial, helvetica, sans-serif; width: calc(60% -
10px); background: rgb(24, 144, 255);">Accept amp;amp; Close</button></div>
<button title="Accept amp;amp; Close" class="message-component message-
button no-children focusable primary accept customizable
sp_choice_type_11" style="padding: 10px 0px; margin: 0px 5px; border-
width: 0px; border-color: rgb(0, 0, 0); border-radius: 5px; border-
style: solid; font-size: 16px; font-weight: 800; color: rgb(255, 255,
255); font-family: arial, helvetica, sans-serif; width: calc(60% -
10px); background: rgb(24, 144, 255);">Accept amp;amp; Close</button>
Ответ №1:
Я перешел по URL-адресу на ваш вопрос, и никакого всплывающего окна не появилось. Но у меня тоже была твоя проблема. В моем случае положить,
import time
time.sleep(4) #change the seconds till it works for you
раньше driver.find_element_by_xpath("//button[@title='Accept amp; Close']").click()
Работал. Второй отсчет потребует небольшой настройки.
Комментарии:
1. я не думаю, что это проблема с ожиданием, я вижу всплывающее окно, но при запуске кода я получаю эту ошибку: Исключение NoSuchElementException: такого элемента нет: Не удается найти элемент: {«метод»:»xpath»,»селектор»:»//кнопка[@title=» Принять и закрыть»]»»} (Информация о сеансе: chrome=93.0.4577.82)
Ответ №2:
Либо применяйте Implicit wait
:
driver.implicitly_wait(10)
driver.get(url)
Или подайте Explicit wait
заявку, как показано ниже, и попробуйте.
driver.get("https://www.marketscreener.com/stock-exchange/calendar/finance/")
time.sleep(10)
wait = WebDriverWait(driver,30)
wait.until(EC.element_to_be_clickable((By.XPATH,"//button[@title='Accept amp; Close']")))
button = driver.find_element_by_xpath("//button[@title='Accept amp; Close']")
# Trial 1
button.click()
# Trial 2
actions = ActionChains(driver)
actions.move_to_element(button).click().perform()
# Trial 3
driver.execute_script("arguments[0].click",button)
time.sleep(5)
Комментарии:
1. я не думаю, что это время ожидания, так как я вижу, как оно появляется, когда я запускаю скрипт. Функция wait.until возвращает ошибку TimeoutException
2. @matthewr — Я сейчас не вижу всплывающего окна. Можете ли вы поделиться HTML-DOM в вопросе
3. добавлена древовидная структура
4. @matthewr — Попробуйте использовать эти xpath
//button[contains(text(),'Close')]
или//button[ends-with(text(),'Close')]
5. по-прежнему говорится NoSuchElementException: нет такого элемента: Не удается найти элемент: {«метод»:»xpath»,»селектор»:»//кнопка[содержит(текст (),» Закрыть»)]»} (Информация о сеансе: chrome=93.0.4577.82)