python selenium-8 Page Object模式
封装空间操作为一个接口使用,而不是直接在页面中查找
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
class Page():
url="https://www.baidu.com"
def __init__(self,driver,base_url=url):
self.base_url = base_url
self.driver=driver
def on_page(self):
print("on_page中的参数self.url"+self.url)
return self.driver.current_url == (self.base_url + self.url)
def _open(self,url):
print("_open传参:"+url)
url = self.base_url + url;
print("整合后的URL:"+url)
self.driver.get(url)
assert self.on_page(),"did not land on %s "%url
def open(self):
self._open(self.url)
def find_element(self,*loc):
return self.driver.find_element(*loc)
class Search(Page):
url='/'
search_key = (By.XPATH,"//input[@id='kw' and @class='s_ipt']")
def type_search(self,word):
self.find_element(*self.search_key).send_keys(word)
def type_submit(self):
self.find_element(By.XPATH,"//input[@id='su']").click()
def test_user_search(driver,word):
search = Search(driver)
search.open()
#通过提供的方法直接操作控件,减少冗余
search.type_search(word)
search.type_submit()
def main():
try:
driver = webdriver.Chrome("/Users/chenshanju/PycharmProjects/SeleniumOfJenkins/driver/chromedriver")
word="hello"
test_user_search(driver,word)
sleep(3)
result_text = driver.find_element_by_xpath("//span[@class='nums_text']").text
assert "百度为您找到相关结果约" in result_text,"结果比对失败"
finally:
driver.quit()
if __name__=="__main__":
main()