【问题标题】:Python + Selenium. CSS Selector or XpathPython + 硒。 CSS 选择器或 Xpath
【发布时间】:2020-10-30 15:04:40
【问题描述】:

如何在https://yandex.ru/ 的提示表中找到 CSS 选择器?

搜索带下划线的 CSS 不起作用 (.mini-suggest__popup.mini-suggest__popup_svg_yes.mini-suggest__popup_theme_flat.mini-suggest__popup_visible)

    browser.implicitly_wait(5)
try:
    suggest = browser.find_element_by_css_selector('.mini-suggest__popup.mini-suggest__popup_svg_yes.mini-suggest__popup_theme_flat.mini-suggest__popup_visible`')
except NoSuchElementException: 
print('no table with hints')

【问题讨论】:

    标签: python selenium selenium-webdriver css-selectors


    【解决方案1】:

    我会使用 CSS 选择器 div.mini-suggest__popup。这是完整的例子:

    from selenium import webdriver
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    
    chrome_options = webdriver.ChromeOptions()
    #chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    
    wd = webdriver.Chrome('<<PATH_TO_CHROMEDRIVER>>', options=chrome_options)
    
    url = 'https://yandex.ru'
    
    # load page via selenium
    wd.get(url)
    
    # wait 5 seconds until page will be loaded
    text_input = WebDriverWait(wd, 5).until(EC.presence_of_element_located((By.ID, 'text')))
    text_input.send_keys('Hello world')
    
    # wait for popup to appear
    popup = WebDriverWait(wd, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div.mini-suggest__popup')))
    
    # wait for popup third child and click it
    WebDriverWait(popup, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'li:nth-child(3)'))).click();
    

    【讨论】:

    • 我可以在不点击弹出第三个孩子的情况下进行检查吗?因为在那之后我必须按 ENTER 并继续测试
    • 当然。在这种情况下,您为最后一个 WebDriverWait 实例提供选择器/xpath,检查其文本而不单击它并继续执行进一步操作。
    • 但是我怎么知道最后一个副本中的文本是什么。所以我需要在测试开始前检查文本?
    • 这取决于您的测试目的。如果需要检查是否显示了建议弹出窗口,则只需获取 li 元素。如果需要检查,显示了多少,您可以检查返回列表的长度。如果需要检查是否显示了某些特定建议,您可以检查是否存在特定文本。
    • 我希望有一些元素会告诉我弹出窗口对用户可见并认为它是 mini-suggest__popup_visible(它是我的 CSS_selector 中的最后一个类) ,它只出现在弹出窗口已打开还是不真实>? :D
    猜你喜欢
    • 2020-04-23
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    相关资源
    最近更新 更多