如何在登录的 selenium 中执行类而不是打开新的 chrome 实例?

2023-12-12

from selenium import webdriver
from time import sleep
filename = "log.txt"
myfile = open(filename, 'w')

class Search(object):
    def __init__(self):
        self.driver = webdriver.Chrome('chromedriver.exe') 

        # "This will open a new chrome instance without being logged in to the site"

        self.driver.get("Site2")
        sleep(2)
        self.driver.find_element_by_xpath("/html/body/div[1]/div[4]/div/div/div[3]/div/div/div[2]/div[2]/div[2]/div/div[4]/div[1]/div[2]/div[1]/a").click()
        sleep(2)
        Texto = self.driver.find_element_by_xpath("/html/body/div[1]/div[4]/div/div/div[4]/div/div/div[1]/div[3]/div/article[1]/div/div[2]/div/div/div/article/div[1]").text
        print(Texto)
        myfile.write(Texto)
        myfile.close()
        sleep(10)
        import re
        Id = re.compile('[0-9]{9}')
        Id2 = re.compile('[0-9]{4}')
        DobMonth = re.compile('[0-9]{2}')
        DobYear = re.compile('[0-9]{2}')
        if Id.match(Texto) and Id2.match(Texto) and DobMonth.match(Texto) and DobYear.match(Texto):
            print ("Matches")
        else:
            print("Not match")
            sleep (20)
            Search()

class BasicBot(object):
    def __init__(self, username, pw):
        self.driver = webdriver.Chrome('chromedriver.exe')
        self.driver.get("site1")
        sleep(2)
        self.driver.find_element_by_xpath("/html/body/div[1]/div[1]/div/div/div/div[1]/a[1]/span").click()
        sleep(2)
        self.driver.find_element_by_xpath("//input[@name=\"login\"]")\
        .send_keys(username)
        self.driver.find_element_by_xpath("//input[@name=\"password\"]")\
        .send_keys(pw)
        self.driver.find_element_by_xpath('/html/body/div[4]/div/div[2]/div/form/div[1]/dl/dd/div/div[2]/button').click()
        sleep(2)
        Search()


BasicBot('username',"password")

所以脚本运行BasicBot(usr,psswd)登录到该网站,并且应该在登录时转到另一个网站,然后搜索 X post 是否符合给定的条件,如果符合,就是这样,如果不符合,我应该刷新该网站并再次检查。


在 Search 类中,您首先创建一个新的 chromedriver 实例:self.driver = webdriver.Chrome('chromedriver.exe'),这就是为什么它会打开另一个具有新鲜状态的窗口。

相反,将您的 Search 类修改为

  1. 获取 webdriver 的现有实例。
  2. 使用脚本打开一个新窗口window.open代替get:
class Search:
    def __init__(self, driver):
        self.driver = driver
        # Open a new window
        self.driver.execute_script("window.open('https://site2')")
        sleep(2) # visually check to make sure it opened

        # Switch to new window
        self.driver.switch_to.window(self.driver.window_handles[-1])
        # After this you can start doing self.driver.find_element_by_xpath and the rest

在BasicBot类中,修改最后一行以传递驱动程序:

Search(self.driver)

最后,您可以使用刷新来刷新您的站点2:

else:
    print("Not match")
    sleep(20)
    self.driver.refresh()

希望能帮助到你。祝你好运!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在登录的 selenium 中执行类而不是打开新的 chrome 实例? 的相关文章

随机推荐