最近在使用selenium为公司同事做了一个自动查单的工具,过程中对selenium了解更多一点,主要遇到的难点就是网站弹窗需要多窗口切换的问题,顺便写了这个工具类,记录下来以备日后可能会用得着。其实selenium本身方法用起来就很方便,制作这个工具主要是个人习惯问题。
class robot(): ''' :parameter driverPath 驱动路径 谷歌的驱动存放路径 :parameter needProxy 是否需要代理,布尔值 :parameter proxy 代理 格式为 xx.xx.xx.xx:8080 :parameter debug 浏览器是否调试模式,需首先启动一个调试模式浏览器,如 chrome.exe --remote-debugging-port=9222 --user-data-dir="d:\facedata\chrome" ''' def __init__(self,driverPath='./chromedriver.exe',needProxy=False,proxy='',debugAddr='127.0.0.1:9000',headless = False): chrome_options = Options() if needProxy: if proxy: chrome_options.add_argument('--proxy-server=%s' % proxy) # OA环境设置代理 else: print('必须设置代理地址') if headless: chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') # chrome_options.add_argument('--user-agent=%s' % ua) if debugAddr: chrome_options.add_experimental_option("debuggerAddress", debugAddr) self.browser = webdriver.Chrome(executable_path=driverPath, chrome_options=chrome_options) ''' 转到网址 :parameter url 即将访问的网址 ''' def redirectURL(self,url): self.browser.get(url) def waitUntil(self,selector): while True: time.sleep(3) try: if self.browser.find_element_by_css_selector(selector): break except Exception as e: print('-->正在等待'+selector+'界面') ''' 获取单个网页元素 ''' def getElementByCssSelecter(self,selecter,parentElement=None): ele = '' try: if parentElement: ele = parentElement.find_element_by_css_selector(selecter) else: ele = self.browser.find_element_by_css_selector(selecter) except Exception as e: print('获取网页元素失败:'+selecter) return ele ''' 获取多个网页元素 ''' def getElementsByCssSelecter(self,selecter,parentElement=None): try: if parentElement: eles = parentElement.find_elements_by_css_selector(selecter) else: eles = self.browser.find_elements_by_css_selector(selecter) except Exception as e: print('获取网页元素s失败:'+selecter + '\n' + str(e)) return eles ''' 移动鼠标到某个网页元素 ''' def moveToElement(self,selecter='',element=None): try: if element: ActionChains(self.browser).move_to_element(element) else: element = self.getElementByCssSelecter(selecter) ActionChains(self.browser).move_to_element(element) except Exception as e: print('移动鼠标到网页元素失败:' + '\n' + str(e)) ''' 点击某个网页元素 ''' def clickElement(self,selecter='',element=None): try: if element: element.click() else: ele = self.getElementByCssSelecter(selecter) ele.click() except Exception as e: print('点击网页元素失败:' + '\n' + str(e)) def randint(self,start, end): return random.randint(start, end) def sendkeytool(self,element, strs): for char in strs: time.sleep(self.randint(10, 40) / 100) element.send_keys(char)
评论
缝纫机
回复不错很好的用的工具http://www.chaussuretods.com/o
缝纫机
回复可以啊,都可以自己制作http://www.abayvn.com/