How to check if some text is present on a web page using selenium 2?

自闭症网瘾萝莉.ら 提交于 2020-05-10 04:04:02

问题


Hi I am using selenium to automate test on web pages. I am using selenium 2 and python and would like to have answers in this framework only. SO how do I check whether some text is present or not? I have tried asset equals but it is not working?

assertEquals(driver.getPageSource().contains("email"), true);

回答1:


You can use driver.page_source and a simple regular expression to check if the text exists:

import re    
src = driver.page_source
text_found = re.search(r'text_to_search', src)
self.assertNotEqual(text_found, None)



回答2:


For those of you who are still interested:

Generic Solution

if (text in driver.page_source):
     # text exists in page

unittest:

assertTrue (text in driver.page_source)

pytest:

assert (text in driver.page_source) 



回答3:


You can try something like

browser = webdriver.Firefox()
browser.get(url)
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, 'some link text')))

Essentially the above lines launch Firefox, navigate to the specified url, cause the browser to hold for 10 seconds, for some url to load then look for a specific link text, if no link text is found, a TimeoutException is triggered.

Please note the number of brackets used, you will run into errors if the number of brackets does not correspond like the above.

To be able to run the above statement, the following must have been declared

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

This uses "element_to_be_clickable" - a full list of wait-conditions can be found here: Selenium Python: Waits



来源:https://stackoverflow.com/questions/10978923/how-to-check-if-some-text-is-present-on-a-web-page-using-selenium-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!