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')
,这就是它打开另一个具有新状态的窗口的原因.
相反,将您的搜索类修改为
- 获取 webdriver 的现有实例。
- 使用脚本
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()
希望有帮助。祝你好运!
关于python - 如何在登录的 selenium 中执行类而不是打开新的 chrome 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60364980/