Python 使用selenium 面向对象方式 无界面或有界面 自动化操作浏览器

这里只是一个示例,实际情况下需要根据要操作的路由而改变代码

from selenium import webdriver
import time

class MyAutoDriver(object):
    def __init__(self):
        # 使用无界面模式
        # chrome_options = webdriver.ChromeOptions()
        # chrome_options.add_argument('--headless')
        # self.brower = webdriver.Chrome(r'/home/aea/chromedriver',chrome_options=chrome_options)
        # 使用有界面模式
        self.brower = webdriver.Chrome(r'/home/aea/chromedriver')
        self.username = 'your account'
        self.password = 'your password'

    def isElementExist(self,id):
        try:
            self.brower.find_element_by_id(id)
            return True
        except:
            return False

    def auto_run(self):
        self.brower.get("https://services.police.govt.nz/vetting")
        while True:
            is_login = self.isElementExist('logon')
            if is_login:
                break
        username_input = self.brower.find_element_by_id('logon:username:input')
        password_input = self.brower.find_element_by_id('logon:password:input')
        username_input.send_keys(self.username)
        password_input.send_keys(self.password)
        self.brower.find_element_by_id('logon:logon').click()
        time.sleep(1)
        self.brower.get("https://services.police.govt.nz/vetting")
        while True:
            agencyRow_list = self.brower.find_elements_by_class_name("agencyRow")
            if len(agencyRow_list) != 0:
                break
        self.brower.find_element_by_class_name('btn-primary').click()
        while True:
            success_list = self.brower.find_elements_by_class_name("alert-success")
            if len(success_list) != 0:
                break
        self.brower.find_element_by_class_name('btn-success').click()
        while True:
            is_Answers = self.isElementExist('questionsAnswers')
            if is_Answers:
                break
        time.sleep(2)

        self.brower.find_element_by_xpath(r'//span[text()="Caregiving - children and youth"]').click()
        time.sleep(1)
        self.brower.find_element_by_xpath(r'//strong[text()="Yes"]').click()
        time.sleep(1)
        self.brower.find_element_by_xpath(r'//div[@id="question1"]//a[text()="NEXT "]').click()
        time.sleep(1)
        self.brower.find_element_by_xpath(r'//strong[text()="Paid"]').click()
        time.sleep(1)
        self.brower.find_element_by_xpath(r'//div[@id="question2"]//a[text()="NEXT "]').click()
        time.sleep(1)
        self.brower.find_element_by_xpath(r'//strong[text()="Optional Police Vet"]').click()
        time.sleep(1)
        self.brower.find_element_by_xpath(r'//div[@id="question3"]//a[text()="NEXT "]').click()
        time.sleep(1)
        print(self.brower.current_url)

new_driver = MyAutoDriver()
new_driver.auto_run()

你可能感兴趣的:(Python)