我有此代码:
driver = webdriver.Chrome()
driver.implicitly_wait(60)
driver.get(link)
driver.add_cookie({'name' : 'access_token', 'value' : token})
driver.refresh()
time.sleep(5)
driver.find_element_by_name('next').click()
time.sleep(5)
如何检查页面上是否存在或标记元素? 我是这样尝试的:
falha = driver.find_element_by_tag_name('h1')
sucesso = driver.find_element_by_tag_name('h2')
if falha.text == "Por segurança":
print ("Retorno: " + element.text + "\nToken: " + token)
if sucesso.text == "Pronto":
print("Retorno: " + element.text + "\nToken: " + token)
driver.close()
但是我的代码只是简单地使元素之一不存在。
答案 0 :(得分:0)
对于documentation,如果找不到指定的元素,则定位方法会引发异常。
如果没有元素具有匹配的名称属性,则为NoSuchElementException 将被提出。
因此,如果不能保证元素的存在,则必须将其包装在try块中,以防止脚本终止。
try:
falha = driver.find_element_by_tag_name('h1')
except:
falha = None
if falha is not None and falha.text == "Por segurança":
print ("Retorno: " + element.text + "\nToken: " + token)
答案 1 :(得分:0)
您可以为此使用driver.find_elements_by_tag_name()
方法,这将为您返回匹配标签元素的列表。
然后,您可以通过使用其大小来确定它是否存在。尝试以下代码:
elementsh1 = driver.find_elements_by_tag_name('h1')
elementsh2 = driver.find_elements_by_tag_name('h2')
if len(elementsh1) > 0 :
print("=> h1 is present...")
print(elementsh1[0].text)
else:
print("=> h1 tags are not there...")
if len(elementsh2) > 0 :
print("=> h2 is present...")
print(elementsh2[0].text)
else:
print("=> h2 tags are not there...")
希望对您有帮助...
答案 2 :(得分:0)
如果存在标签“ h1”,请运行尝试代码,如果存在标签“ h2”,请运行
try:
element = driver.find_elements_by_tag_name('h1')
print ("Retorno: " + element.text + "\nToken: " + token)
except:
element = driver.find_element_by_tag_name('h2')
print("Retorno: " + element.text + "\nToken: " + token)
finally:
driver.close()
答案 3 :(得分:0)
此代码处理所有错误
try:
falha = driver.find_element_by_tag_name('h1')
for ele in falha:
if ele.text == "Por segurança":
print("Retorno: " + element.text + "\nToken: " + token)
except Exception as e:
print(e)
try:
sucesso = driver.find_element_by_tag_name('h2')
for ele in sucesso:
if ele.text == "Pronto":
print("Retorno: " + element.text + "\nToken: " + token)
except Exception as e:
print(e)