不能在Selenium中使用If/Elif/Else语句——确定元素是否存在



我正在尝试为谷歌搜索结果建立一个webscraper &我已经提出了三个场景来处理:

  1. 出现一个弹出框,其中包含我需要的信息,并提取该信息弹出框
  2. 标题下面的文本有信息&我提取出来
  3. 标题下的文本没有有用的信息-我只是抓取链接抓取链接本身

这是我的代码,我假设使用"if"语句的意思是,如果webdriver不能检测到该元素,那就意味着它要转到下一行代码。但是,我遇到了这个错误

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".hgKElc"}
(Session info: headless chrome=87.0.4280.66)

我特别选择了这个类名,因为我知道在简化流程的某些页面(在#2和#3中)会缺少它。如何让机器忽略未找到的元素& &;继续下一件事?

我代码:

#preparing brand name
brand_name = 'agentnateur'
sh_brand_name = brand_name.lower().replace(' ','')

#google search
wd.get('https://www.google.com/')
time.sleep(3)
subject_box = wd.find_element_by_css_selector('input[name=q]')
search_stg = '@'+ sh_brand_name +'.com contact us'
print(search_stg)
subject_box.send_keys(search_stg)
subject_box.submit()
time.sleep(5)
#extracting information -- case 1 pop up box
html = wd.page_source
if wd.find_element_by_class_name('hgKElc'): 
email_address = wd.find_element_by_class_name('hgKElc')
print('yes1')
elif wd.find_element_by_class('aCOpRe').find_element_by_xpath("//*[contains(text(),'Contact')]"): 
email_address = wd.find_element_by_class('aCOpRe').find_element_by_xpath("//*[contains(text(),'Contact')]")
print('yes2')
elif wd.find_element_by_class('aCOpRe').find_element_by_xpath("//*[contains(text(),'contact')]"): 
email_address = wd.find_element_by_class('aCOpRe').find_element_by_xpath("//*[contains(text(),'contact')]")
print('yes3')
else: 
email_address = wd.find_element_by_class('yuRUbf').find_element_by_css_selector('#rso > div:nth-child(1) > div > div.yuRUbf > a')

print(email_address)
wd.quit()

我已经尝试了3块try,例外,但这不起作用,因为我需要循环继续运行以后的迭代。要做到这一点,我理想情况下需要一个continue函数,但这在try, exception块中不起作用。

非常感谢您的帮助!

if wd.find_elements_by_class_name('hgKElc'): 
email_address = wd.find_element_by_class_name('hgKElc')
print('yes1')
elif wd.find_element_by_class('aCOpRe').find_elements_by_xpath("//*[contains(text(),'Contact')]"): 
email_address = wd.find_element_by_class('aCOpRe').find_element_by_xpath("//*[contains(text(),'Contact')]")
print('yes2')
elif wd.find_element_by_class('aCOpRe').find_elements_by_xpath("//*[contains(text(),'contact')]"): 
email_address = wd.find_element_by_class('aCOpRe').find_elements_by_xpath("//*[contains(text(),'contact')]")
print('yes3')
else: 
email_address = wd.find_element_by_class('yuRUbf').find_element_by_css_selector('#rso > div:nth-child(1) > div > div.yuRUbf > a')

find_element返回一个web元素,否则如果element不存在则抛出异常。你不能用它来驱动像if这样的条件分支。

使用find_elements代替。这将返回一个包含与定位符匹配的web元素的列表,如果没有找到元素则返回空列表

在python中

空list[]为False,非空list[1,2,3]为True

最新更新