首页 > 解决方案 > If/else 语句取决于 Selenium 中是否存在 xpath

问题描述

我不清楚如何在 if/else 语句中检查特定 xpath 的存在(我也不确定使用 xpaths 是否是最好的方法)。

我本质上想要执行以下操作(使用链接到可能存在或不完整的搜索结果的 URL 列表):

对于每个 URL:

  1. 检查是否存在相应的搜索结果页面
  2. 如果存在,请检查是否存在“更多信息”按钮
  3. 如果存在,请检查每个数据字段是否存在/是否已填充
  4. 对于所有空字段/部分/页面,用空格填写字典

我已经尝试通过定义一个函数来检查是否存在 xpath,并在嵌套的 if/else 语句中使用它,但这些都返回错误。

当前代码如下:

检查 xpath 是否存在的函数(布尔值):

def hasxpath(xpath):
    try: 
        driver.find_element_by_xpath(xpath)
        return True
    except:
        return False

处理 URL 列表的代码:

for url in urls:
    driver = webdriver.Chrome(executable_path='/xxx')
    driver.get(url)

    # Check if search result page exists
    if hasxpath('xxx') == True:

        # If 'More Info' button exists, click it
        if hasxpath('xxx') == True:
            driver.find_element_by_xpath('xxx').click()

            # For each field, check if it exists and if so collect data
            # (example below for 'Name' field)
            if hasxpath('xxx') == True:
                name = driver.find_element_by_xpath('xxx')
                name = name.text
            else:
                name = ''
            driver.close()

        else:
            driver.close()

    else:
        driver.close()

当页面不存在时,这似乎仍然不起作用(它会引发错误而不是执行 driver.close()。有没有简单的解决方法?或者甚至是检查这些信息和定位数据的更好方法(而不是使用xpaths)?

标签: pythonseleniumselenium-webdriver

解决方案


您的代码看起来不错。我已经检查过没有 Xpath 它正在关闭浏览器。请运行我的代码并对您的 url 和 xpath 进行必要的更改。

from selenium import webdriver
import time

def hasxpath(xpath):
    try:
        driver.find_element_by_xpath(xpath)
        return True
    except:
        return False

url_list = ["https://www.google.com/", "https://www.w3schools.com/","https://www.toolsqa.com/"]

for url in url_list:
    driver = webdriver.Chrome('D:/Java/TestChrome/lib/chromedriver.exe')
    print(url)
    driver.get(url)
    time.sleep(3)
    if hasxpath('xxx') == True:

        if hasxpath('xxx') == True:
            driver.find_element_by_xpath('xxx').click()

            # For each field, check if it exists and if so collect data
            # (example below for 'Name' field)
            if hasxpath('xxx') == True:
                name = driver.find_element_by_xpath('xxx')
                name = name.text
            else:
                name = ''
            driver.close()

        else:
            driver.close()

    else:
        driver.close()
        print('Closing Browser : ' + url)

print('pass')  

推荐阅读