python - If/else 语句取决于 Selenium 中是否存在 xpath
问题描述
我不清楚如何在 if/else 语句中检查特定 xpath 的存在(我也不确定使用 xpaths 是否是最好的方法)。
我本质上想要执行以下操作(使用链接到可能存在或不完整的搜索结果的 URL 列表):
对于每个 URL:
- 检查是否存在相应的搜索结果页面
- 如果存在,请检查是否存在“更多信息”按钮
- 如果存在,请检查每个数据字段是否存在/是否已填充
- 对于所有空字段/部分/页面,用空格填写字典
我已经尝试通过定义一个函数来检查是否存在 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)?
解决方案
您的代码看起来不错。我已经检查过没有 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')
推荐阅读
- ssh - 在我几乎无法控制服务器的情况下,如何通过 SSH 连接轻松编辑文件?
- django - 在 Django 上进行 Post 预览的最有效方法是什么?
- javascript - 如何使其多部分选择过滤角度
- python - Scipy 最小化迭代过去的界限
- r - 如何遍历列表并使用前一个元素?
- sql - 如果外键是另一个表的主键,为什么它可以为空?
- visual-c++ - 出现错误 LNK2019:使用 MSVC 在 Windows 中编译 SDL2 代码时出现无法解析的外部符号
- c - Why `pow(sum,1/2)` is not giving me the same result as `sqrt(sum))`?
- firebase - Flutter/Firebase 实时数据库:如何使用 equalsTo?
- listview - TListView 项目详细字体到等宽字体