我有这个脚本可以转到谷歌外卖并下载外卖文件。我遇到的问题是,某些帐户在单击“Takeout_dlbtn”时需要重新登录,而其他帐户可以直接下载。我试图把这个 IF ELSE 语句。如果显示“密码”,我们按照步骤重新输入密码,然后下载。如果没有出现“密码”,我们假设我们不需要登录并且可以立即下载。
我遇到的问题是,我的 IF 语句运行,如果显示密码页面,它将输入密码然后下载。但是如果没有显示密码页面,IF 语句仍会运行,而我的 ELSE 语句不会被执行。它抛出这个错误“没有这样的元素:无法定位元素:{“方法”:“css select”,“选择器”:“[名称-“密码”]“}”
如果未显示“密码”元素,我如何让 ELSE 函数运行?任何帮助将不胜感激。
def DLTakeout(self, email, password):
self.driver.get("https://takeout.google.com/")
time.sleep(2)
self.driver.find_element_by_xpath(takeout_DLbtn).click()
time.sleep(4)
if self.driver.find_element_by_name("password").is_displayed():
print("IF statement")
time.sleep(3)
self.driver.find_element_by_name("password").clear()
time.sleep(5)
self.driver.find_element_by_name("password").send_keys(password)
time.sleep(5)
self.driver.find_element_by_xpath("//*[@id='passwordNext']/div/button/div[2]").click()
print("Downloading")
logging.info("Downloading")
time.sleep(10) #change time.sleep to a higher number when download file is in gbs #1500
self.write_yaml(email)
print("Write to yaml successfully")
logging.info("Write to yaml successfully")
print("Zip move process about to start")
logging.info("Zip move process about to start")
time.sleep(4)
else:
print("else statement")
time.sleep(5)
print("Downloading")
logging.info("Downloading")
答案 0 :(得分:0)
根据 Selenium 文档:
<块引用>4.2.按名称定位
当您知道元素的 name 属性时使用它。有了这个
策略,具有匹配名称属性的第一个元素将是
回来。如果没有元素具有匹配的 name 属性,则
NoSuchElementException
将被提升。
因此,不要使用 if/else,而是尝试使用 try/catch 块:
try:
self.driver.find_element_by_name("password")
print ("if statement")
...
except NoSuchElementException:
print ("else statement")
...