Python 2.7 如何通过Python使用Selenium从元素中获取文本
我正在为一个网站编写一个自动脚本,并希望验证是否创建了一个表单。我已经创建了我命名为“Blah!”的表单 该网页现在将有一个列标题为“Name”的表单,其中显示了“Blah” 在html文件的某个地方会有一个名为“Blah”的字符串。我试图获取包含该字符串的html并将其设置为一个变量,然后进行比较以查看该变量是否包含“blah”。使用python时,应如下所示:Python 2.7 如何通过Python使用Selenium从元素中获取文本,python-2.7,selenium,selenium-webdriver,webdriver,Python 2.7,Selenium,Selenium Webdriver,Webdriver,我正在为一个网站编写一个自动脚本,并希望验证是否创建了一个表单。我已经创建了我命名为“Blah!”的表单 该网页现在将有一个列标题为“Name”的表单,其中显示了“Blah” 在html文件的某个地方会有一个名为“Blah”的字符串。我试图获取包含该字符串的html并将其设置为一个变量,然后进行比较以查看该变量是否包含“blah”。使用python时,应如下所示: x = driver.find_element_by_xpath(Some_code_to_catch_the_html) prin
x = driver.find_element_by_xpath(Some_code_to_catch_the_html)
print ("blah" in x) #return true is x includes the string- form was created!
我能够运行的代码没有任何错误,除了没有找到文本“blah!”。
注意:“blah!”的Div没有唯一的id,因此我必须使用该块的id
实际代码:
element = driver.find_elements_by_xpath("//*[@id='dashboard-container-d08a6dcd-dc17-4662-9156-7fe74a4abc15']")
print(element[0].text)
assert "blah!" in element, "text not found in element"
# I have also used 'element without the index.
# here is the actual id for the table where 'blah!'is created under >> //*[@id='dashboard-container-d08a6dcd-dc17-4662-9156-7fe74a4abc15']/div[1]/div[2]/div/div/form/div[5]/table/tbody
在什么情况下,文本不会从html返回 要验证任何特定页面源中是否包含某个元素/文本/表单,您可以使用
驱动程序在Page\u Source
中搜索该元素/文本/表单,并且可以遵循以下解决方案:
- 代码块:
from selenium import webdriver from selenium.webdriver.common.keys import Keys driver.get("http://www.python.org") print("Don Powell" in driver.page_source) elem = driver.find_element_by_name("q") elem.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN) print("Don Powell" not in driver.page_source)
- 控制台输出:
False True