Selenium Python 点击​​只有一半的时间有效

但我正在尝试为我的网站编写一个单元测试,该测试会遍历所有链接,并在网站正常工作时返回“A ok”或“no go”。但我在使用该程序时遇到了问题,它无法不断单击站点导航栏中的链接。我尝试过多次隐式等待。明确的预期条件,但页面加载时,有一半的时间会单击链接并转到网站的该部分,而另一半的程序只是停止,没有单击任何内容。


from selenium import webdriver

from selenium.webdriver.common.keys import Keys

import time

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver import ActionChains


PATH = "C:\Program Files (x86)\chromedriver.exe"


drive = webdriver.Chrome(PATH)

drive.get("https://www.blackhempfamily.com/")


wait = WebDriverWait(drive, 10)

link = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Why Black Hemp?")))

link.click()


心有法竹
浏览 169回答 4
4回答

MMMHUHU

将是一个更好使用的标签。wait.until(EC.element_to_be_clickable((By.XPATH, "//p[text()='Why Black Hemp?']")))

临摹微笑

尝试使用 xpath 代替,并使用要定位的元素(不可单击),因为它是一个段落。这对我有用:from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport timefrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver import ActionChainsPATH = "C:\Program Files (x86)\chromedriver.exe"drive = webdriver.Chrome(PATH)drive.get("https://www.blackhempfamily.com/")linkWait = EC.element_to_be_located((By.XPATH, "//div/p[contains(., 'Why Black Hemp?')]"))WebDriverWait(drive, 10).until(linkWait)link = drive.find_element_by_xpath("//div/p[contains(., 'Why Black Hemp?')]")link.click()

开心每一天1111

所以,花了一段时间......但是,我认为我能够解决这个问题。您需要执行的操作是:点击“为什么是黑大麻?”等待页面停止滚动滚动到页面顶部等待页面停止滚动**尝试向下滚动以便可以nav显示该栏重复直到您满意/通过“A-OK”测试为了实现这一点,您需要导入以下内容from selenium import webdriverfrom selenium.webdriver.chrome.webdriver import WebDriver as ChromeWebDriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWait as DriverWaitfrom selenium.webdriver.support import expected_conditions as DriverConditionsfrom selenium.common.exceptions import WebDriverExceptionimport time第 1 步 - 点击“为什么是黑大麻?” nav条形元素chrome_driver.find_element(By.XPATH, "//nav[contains(@id, 'navContainer')]//p[text()='Why Black Hemp?']/../../..").click()第 2 步 - 检查页面是否仍在滚动# Checks to see if our page is still scrolling    while is_same_position == False:        windowPosition1 = chrome_driver.execute_script("return document.body.scrollHeight;")        time.sleep(2)        windowPosition2 = chrome_driver.execute_script("return document.body.scrollHeight;")        if(windowPosition1 == windowPosition2):            is_same_position = True            final_window_position = windowPosition1第 3 步 - 滚动到页面顶部chrome_driver.execute_script("window.scrollTo(0, {0})".format((0 - final_window_position)))第 4 步 - 检查页面是否仍在滚动# Checks to see if our page is still scrolling    while is_same_position == False:        windowPosition1 = chrome_driver.execute_script("return document.body.scrollHeight;")        time.sleep(2)        windowPosition2 = chrome_driver.execute_script("return document.body.scrollHeight;")        if(windowPosition1 == windowPosition2):            is_same_position = True第 5 步 - 尝试向下滚动,直到我们的header标签没有styleofvisibility: hidden# Scrolls down until our nav bar is displayed    for scrollNum in range(10):        chrome_driver.execute_script("window.scrollTo(0, {0})".format(scrollNum * 100 + 200))        time.sleep(2)        if is_displayed(chrome_driver, "//header[contains(@style, 'visibility: hidden')]") == False:            break第 6 步 - 重复直到您满意为止主要代码 - 供参考from selenium import webdriverfrom selenium.webdriver.chrome.webdriver import WebDriver as ChromeWebDriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWait as DriverWaitfrom selenium.webdriver.support import expected_conditions as DriverConditionsfrom selenium.common.exceptions import WebDriverExceptionimport timedef get_chrome_driver():    """This sets up our Chrome Driver and returns it as an object"""    chrome_options = webdriver.ChromeOptions()     chrome_options.add_argument("window-size=1500,1000")            # Removes the "This is being controlled by automation" alert / notification    chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])    path_to_chrome = "F:\Selenium_Drivers\Windows_Chrome85_Driver\chromedriver.exe"    return webdriver.Chrome(executable_path = path_to_chrome,                            options = chrome_options)def wait_displayed(driver : ChromeWebDriver, xpath : str, int = 3):    try:        DriverWait(driver, int).until(            DriverConditions.presence_of_element_located(locator = (By.XPATH, xpath))        )    except:        raise WebDriverException(f'Timeout: Failed to find {xpath}')    def is_displayed(driver : ChromeWebDriver, xpath : str, int = 3):    try:        webElement = DriverWait(driver, int).until(            DriverConditions.presence_of_element_located(locator = (By.XPATH, xpath))        )        return True if webElement != None else False    except:        return False# Gets our chrome driver and opens our sitechrome_driver = get_chrome_driver()chrome_driver.get("https://www.blackhempfamily.com/")# Repeats this 5 timesfor repeat in range(5):    print("Attempt to click our link. Try #{0}".format(repeat + 1))        is_same_position = False    final_window_position = 0        # Checks to see if our website's elements display    wait_displayed(chrome_driver, "//nav[contains(@id, 'navContainer')]")    wait_displayed(chrome_driver, "//nav[contains(@id, 'navContainer')]//p[text()='Why Black Hemp?']")    wait_displayed(chrome_driver, "//nav[contains(@id, 'navContainer')]//p[text()='Shop Black Hemp']")    # Clicks our "Why Black Hemp?" tab    chrome_driver.find_element(By.XPATH, "//nav[contains(@id, 'navContainer')]//p[text()='Why Black Hemp?']/../../..").click()        # Checks to see if our page is still scrolling    while is_same_position == False:        windowPosition1 = chrome_driver.execute_script("return document.body.scrollHeight;")        time.sleep(2)        windowPosition2 = chrome_driver.execute_script("return document.body.scrollHeight;")        if(windowPosition1 == windowPosition2):            is_same_position = True            final_window_position = windowPosition1        # Checks to see if our "Natural Moisture" text displays    wait_displayed(chrome_driver, "(//h2//span[contains(., 'Natural Moisture')]/../..)[1]")        # Scrolls back to the top of the page    chrome_driver.execute_script("window.scrollTo(0, {0})".format((0 - final_window_position)))    is_same_position = False        # Checks to see if our page is still scrolling    while is_same_position == False:        windowPosition1 = chrome_driver.execute_script("return document.body.scrollHeight;")        time.sleep(2)        windowPosition2 = chrome_driver.execute_script("return document.body.scrollHeight;")        if(windowPosition1 == windowPosition2):            is_same_position = True        # Scrolls down until our nav bar is displayed    for scrollNum in range(10):        chrome_driver.execute_script("window.scrollTo(0, {0})".format(scrollNum * 100 + 200))        time.sleep(2)        if is_displayed(chrome_driver, "//header[contains(@style, 'visibility: hidden')]") == False:            breakchrome_driver.quit()chrome_driver.stop_client()print('Congratulations! You clicked your link multiple times!')

ABOUTYOU

您正在搜索的元素不是链接。这是一个段落(p)。我添加了一个sleep调用以使页面有更多的加载时间。试试这个代码:time.sleep(3)wait = WebDriverWait(drive, 10)#link = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Why Black Hemp?")))link = drive.find_element_by_xpath('//*[@id="idh09fqo2label"]')link.click()
打开App,查看更多内容
随时随地看视频慕课网APP