为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
心有法竹 2023-11-09 20:18:23
但我正在尝试为我的网站编写一个单元测试,该测试会遍历所有链接,并在网站正常工作时返回“A ok”或“no go”。但我在使用该程序时遇到了问题,它无法不断单击站点导航栏中的链接。我尝试过多次隐式等待。明确的预期条件,但页面加载时,有一半的时间会单击链接并转到网站的该部分,而另一半的程序只是停止,没有单击任何内容。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/")wait = WebDriverWait(drive, 10)link = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Why Black Hemp?")))link.click()
查看完整描述

4 回答

?
MMMHUHU

TA贡献1834条经验 获得超8个赞

将是一个更好使用的标签。

wait.until(EC.element_to_be_clickable((By.XPATH, "//p[text()='Why Black Hemp?']")))



查看完整回答
反对 回复 2023-11-09
?
临摹微笑

TA贡献1982条经验 获得超2个赞

尝试使用 xpath 代替,并使用要定位的元素(不可单击),因为它是一个段落。这对我有用:


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/")


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()


查看完整回答
反对 回复 2023-11-09
?
开心每一天1111

TA贡献1836条经验 获得超13个赞

所以,花了一段时间......但是,我认为我能够解决这个问题。您需要执行的操作是:

  1. 点击“为什么是黑大麻?”

  2. 等待页面停止滚动

  3. 滚动到页面顶部

  4. 等待页面停止滚动

  5. **尝试向下滚动以便可以nav显示该栏

  6. 重复直到您满意/通过“A-OK”测试

为了实现这一点,您需要导入以下内容

from selenium import webdriver

from selenium.webdriver.chrome.webdriver import WebDriver as ChromeWebDriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait as DriverWait

from selenium.webdriver.support import expected_conditions as DriverConditions

from selenium.common.exceptions import WebDriverException

import 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 webdriver

from selenium.webdriver.chrome.webdriver import WebDriver as ChromeWebDriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait as DriverWait

from selenium.webdriver.support import expected_conditions as DriverConditions

from selenium.common.exceptions import WebDriverException

import time



def 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 site

chrome_driver = get_chrome_driver()

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



# Repeats this 5 times

for 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:

            break



chrome_driver.quit()

chrome_driver.stop_client()

print('Congratulations! You clicked your link multiple times!')



查看完整回答
反对 回复 2023-11-09
?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

您正在搜索的元素不是链接。这是一个段落(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()


查看完整回答
反对 回复 2023-11-09
  • 4 回答
  • 0 关注
  • 84 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信