日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

(下)python3 selenium3 从框架实现代码学习selenium让你事半功倍

發(fā)布時間:2023/12/4 python 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (下)python3 selenium3 从框架实现代码学习selenium让你事半功倍 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

上一篇博文簡要

在上一篇博文中已得知:使用 execute 向遠程服務器發(fā)送請求會通過 webdriver 與瀏覽器交互,且發(fā)送已定義的命令常量可獲得一些相關(guān)信息。

其中 execute 方法實現(xiàn)已經(jīng)在上一篇博文中有實現(xiàn)說明。并且在我們已經(jīng)知道 webdriver基類(selenium.webdriver.remote.webdriver)中,實現(xiàn)了操作頁面元素的基本方法。

通過簡單運用全面學習

假設(shè)現(xiàn)在需要打開百度,搜索“CSDN A757291228”該如何進行操作呢?
通過查找 webdriver基類(selenium.webdriver.remote.webdriver)找到了以下幾個查找元素的方法:

def find_element_by_id(self, id_):"""Finds an element by id.:Args:- id\_ - The id of the element to be found.:Returns:- WebElement - the element if it was found:Raises:- NoSuchElementException - if the element wasn't found:Usage:element = driver.find_element_by_id('foo')"""return self.find_element(by=By.ID, value=id_)def find_elements_by_id(self, id_):"""Finds multiple elements by id.:Args:- id\_ - The id of the elements to be found.:Returns:- list of WebElement - a list with elements if any was found. Anempty list if not:Usage:elements = driver.find_elements_by_id('foo')"""return self.find_elements(by=By.ID, value=id_)def find_element_by_xpath(self, xpath):"""Finds an element by xpath.:Args:- xpath - The xpath locator of the element to find.:Returns:- WebElement - the element if it was found:Raises:- NoSuchElementException - if the element wasn't found:Usage:element = driver.find_element_by_xpath('//div/td[1]')"""return self.find_element(by=By.XPATH, value=xpath)def find_elements_by_xpath(self, xpath):"""Finds multiple elements by xpath.:Args:- xpath - The xpath locator of the elements to be found.:Returns:- list of WebElement - a list with elements if any was found. Anempty list if not:Usage:elements = driver.find_elements_by_xpath("//div[contains(@class, 'foo')]")"""return self.find_elements(by=By.XPATH, value=xpath)def find_element_by_link_text(self, link_text):"""Finds an element by link text.:Args:- link_text: The text of the element to be found.:Returns:- WebElement - the element if it was found:Raises:- NoSuchElementException - if the element wasn't found:Usage:element = driver.find_element_by_link_text('Sign In')"""return self.find_element(by=By.LINK_TEXT, value=link_text)def find_elements_by_link_text(self, text):"""Finds elements by link text.:Args:- link_text: The text of the elements to be found.:Returns:- list of webelement - a list with elements if any was found. anempty list if not:Usage:elements = driver.find_elements_by_link_text('Sign In')"""return self.find_elements(by=By.LINK_TEXT, value=text)def find_element_by_partial_link_text(self, link_text):"""Finds an element by a partial match of its link text.:Args:- link_text: The text of the element to partially match on.:Returns:- WebElement - the element if it was found:Raises:- NoSuchElementException - if the element wasn't found:Usage:element = driver.find_element_by_partial_link_text('Sign')"""return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text)def find_elements_by_partial_link_text(self, link_text):"""Finds elements by a partial match of their link text.:Args:- link_text: The text of the element to partial match on.:Returns:- list of webelement - a list with elements if any was found. anempty list if not:Usage:elements = driver.find_elements_by_partial_link_text('Sign')"""return self.find_elements(by=By.PARTIAL_LINK_TEXT, value=link_text)def find_element_by_name(self, name):"""Finds an element by name.:Args:- name: The name of the element to find.:Returns:- WebElement - the element if it was found:Raises:- NoSuchElementException - if the element wasn't found:Usage:element = driver.find_element_by_name('foo')"""return self.find_element(by=By.NAME, value=name)def find_elements_by_name(self, name):"""Finds elements by name.:Args:- name: The name of the elements to find.:Returns:- list of webelement - a list with elements if any was found. anempty list if not:Usage:elements = driver.find_elements_by_name('foo')"""return self.find_elements(by=By.NAME, value=name)def find_element_by_tag_name(self, name):"""Finds an element by tag name.:Args:- name - name of html tag (eg: h1, a, span):Returns:- WebElement - the element if it was found:Raises:- NoSuchElementException - if the element wasn't found:Usage:element = driver.find_element_by_tag_name('h1')"""return self.find_element(by=By.TAG_NAME, value=name)def find_elements_by_tag_name(self, name):"""Finds elements by tag name.:Args:- name - name of html tag (eg: h1, a, span):Returns:- list of WebElement - a list with elements if any was found. Anempty list if not:Usage:elements = driver.find_elements_by_tag_name('h1')"""return self.find_elements(by=By.TAG_NAME, value=name)def find_element_by_class_name(self, name):"""Finds an element by class name.:Args:- name: The class name of the element to find.:Returns:- WebElement - the element if it was found:Raises:- NoSuchElementException - if the element wasn't found:Usage:element = driver.find_element_by_class_name('foo')"""return self.find_element(by=By.CLASS_NAME, value=name)def find_elements_by_class_name(self, name):"""Finds elements by class name.:Args:- name: The class name of the elements to find.:Returns:- list of WebElement - a list with elements if any was found. Anempty list if not:Usage:elements = driver.find_elements_by_class_name('foo')"""return self.find_elements(by=By.CLASS_NAME, value=name)def find_element_by_css_selector(self, css_selector):"""Finds an element by css selector.:Args:- css_selector - CSS selector string, ex: 'a.nav#home':Returns:- WebElement - the element if it was found:Raises:- NoSuchElementException - if the element wasn't found:Usage:element = driver.find_element_by_css_selector('#foo')"""return self.find_element(by=By.CSS_SELECTOR, value=css_selector)def find_elements_by_css_selector(self, css_selector):"""Finds elements by css selector.:Args:- css_selector - CSS selector string, ex: 'a.nav#home':Returns:- list of WebElement - a list with elements if any was found. Anempty list if not:Usage:elements = driver.find_elements_by_css_selector('.foo')"""return self.find_elements(by=By.CSS_SELECTOR, value=css_selector) def find_element(self, by=By.ID, value=None):"""Find an element given a By strategy and locator. Prefer the find_element_by_* methods whenpossible.:Usage:element = driver.find_element(By.ID, 'foo'):rtype: WebElement"""if self.w3c:if by == By.ID:by = By.CSS_SELECTORvalue = '[id="%s"]' % valueelif by == By.TAG_NAME:by = By.CSS_SELECTORelif by == By.CLASS_NAME:by = By.CSS_SELECTORvalue = ".%s" % valueelif by == By.NAME:by = By.CSS_SELECTORvalue = '[name="%s"]' % valuereturn self.execute(Command.FIND_ELEMENT, {'using': by,'value': value})['value']def find_elements(self, by=By.ID, value=None):"""Find elements given a By strategy and locator. Prefer the find_elements_by_* methods whenpossible.:Usage:elements = driver.find_elements(By.CLASS_NAME, 'foo'):rtype: list of WebElement"""if self.w3c:if by == By.ID:by = By.CSS_SELECTORvalue = '[id="%s"]' % valueelif by == By.TAG_NAME:by = By.CSS_SELECTORelif by == By.CLASS_NAME:by = By.CSS_SELECTORvalue = ".%s" % valueelif by == By.NAME:by = By.CSS_SELECTORvalue = '[name="%s"]' % value# Return empty list if driver returns null# See https://github.com/SeleniumHQ/selenium/issues/4555return self.execute(Command.FIND_ELEMENTS, {'using': by,'value': value})['value'] or []

從以上實現(xiàn)的方法中,execute 方法實現(xiàn)在這里不在贅述實現(xiàn),上一節(jié)已有說明,本節(jié)主要介紹方法使用。

首先查看 find_element_by_id 方法的使用,在方法說明中已經(jīng)介紹使用方法:

element = driver.find_element_by_id('foo')

該方法注釋說明為(以下為了清晰說明,使用截圖展示注釋):

通過注釋說明得知,find_element_by_id 方法找到id為指定值的元素,并返回這個元素。

查看具體實現(xiàn)為:

self.find_element(by=By.ID, value=id_)

以上實現(xiàn)調(diào)用了 find_element 方法,并且傳入 by的值為By.ID,隨后傳入具體值;首先查看By類(selenium.webdriver.common.by):

class By(object):"""Set of supported locator strategies."""ID = "id"XPATH = "xpath"LINK_TEXT = "link text"PARTIAL_LINK_TEXT = "partial link text"NAME = "name"TAG_NAME = "tag name"CLASS_NAME = "class name"CSS_SELECTOR = "css selector"

這個類與Command(selenium.webdriver.remote.command)類作用類似,上節(jié)已說明Command在這里也不過多說明By。

在這里查看 find_element 方法實現(xiàn):

def find_element(self, =By.ID, value=None):"""Find an element given a By strategy and locator. Prefer the find_element_by_* methods whenpossible.:Usage:element = driver.find_element(By.ID, 'foo'):rtype: WebElement"""if self.w3c:if by == By.ID:by = By.CSS_SELECTORvalue = '[id="%s"]' % valueelif by == By.TAG_NAME:by = By.CSS_SELECTORelif by == By.CLASS_NAME:by = By.CSS_SELECTORvalue = ".%s" % valueelif by == By.NAME:by = By.CSS_SEhj0ECTORvalue = '[name="%s"]' % valuereturn self.execute(Command.FIND_ELEMENT, {'using': by,'value': value})['value']

以上類首先判斷查找類型,隨后進行值的拼接,最后把查找方式和值傳入 execute 方法中,隨后返回元素對象。

幾乎所有的元素查找方法,實現(xiàn)相同,我們簡單實用這個函數(shù)。

寫代碼前,我們需要打開百度網(wǎng)址,審查元素查找id值:

得到輸入框的id值為kw,那么代碼應該如下:

from selenium import webdriver driver = webdriver.Chrome() driver.get("https://www.baidu.com/") input = driver.find_element_by_id('kw')# print('作者博客:https://blog.csdn.net/A757291228') #支持原創(chuàng),轉(zhuǎn)載請貼上鏈接

由于查到到元素后返回的是元素對象:

在元素類(selenium.webdriver.remote.webelement)中查找方法,找到如下方法:

def send_keys(self, *value):"""Simulates typing into the element.:Args:- value - A string for typing, or setting form fields. For settingfile inputs, this could be a local file path.Use this to send simple key events or to fill out form fields::form_textfield = driver.find_element_by_name('username')form_textfield.send_keys("admin")This can also be used to set file inputs.::file_input = driver.find_element_by_name('profilePic')file_input.send_keys("path/to/profilepic.gif")# Generally it's better to wrap the file path in one of the methods# in os.path to return the actual path to support cross OS testing.# file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))"""# transfer file to another machine only if remote driver is used# the same behaviour as for java bindingif self.parent._is_remote:local_file = self.parent.file_detector.is_local_file(*value)if local_file is not None:value = self._upload(local_file)self._execute(Command.SEND_KEYS_TO_ELEMENT,{'text': "".join(keys_to_typing(value)),'value': keys_to_typing(value)}) # Private Methodsdef _execute(self, command, params=None):"""Executes a command against the underlying HTML element.Args:command: The name of the command to _execute as a string.params: A dictionary of named parameters to send with the command.Returns:The command's JSON response loaded into a dictionary object."""if not params:params = {}params['id'] = self._idreturn self._parent.execute(command, params)

得知 send_keys 也是通過 execute 發(fā)送命令得到結(jié)果。在注釋說明中得到了 send_keys 的使用方法為:

form_textfield.send_keys("admin")

我們修改之前的代碼:

from selenium import webdriver driver = webdriver.Chrome() driver.get("https://www.baidu.com/") input = driver.find_element_by_id('kw') input.send_keys("CSDN A757291228")# print('作者博客:https://blog.csdn.net/A757291228') #支持原創(chuàng),轉(zhuǎn)載請貼上鏈接

最后還查個點擊即可完成自動化搜索功能;我們繼續(xù)查看元素類,找到如下方法:

def click(self):"""Clicks the element."""self._execute(Command.CLICK_ELEMENT)

click 方法與 send_keys 方法實現(xiàn)相同,不在贅述。直接使用click方法即可進行元素的點擊。查找百度搜索點擊按鈕的id:

修改代碼如下:

from selenium import webdriver driver = webdriver.Chrome() driver.get("https://www.baidu.com/") input = driver.find_element_by_id('kw') input.send_keys("CSDN A757291228") enter = driver.find_element_by_id('su') enter.click() # print('作者博客:https://blog.csdn.net/A757291228') #支持原創(chuàng),轉(zhuǎn)載請貼上鏈接

運行結(jié)果如下:

總結(jié)

我們簡單的學習了使用 selenium 打開瀏覽器搜索 了“CSDN A757191228” ,在這個簡單的例子的學習中,學習到的不僅是這個例子原本的那幾行代碼;通過實現(xiàn)分析,了解了其它功能函數(shù)所在的位置,可以通過這些功能函數(shù),實現(xiàn)自己想要的功能!

從框架實現(xiàn)上分析可以事半功倍的學習框架的使用,以及了解框架的實現(xiàn)原理,更加利于我們的開發(fā)使用。

總結(jié)

以上是生活随笔為你收集整理的(下)python3 selenium3 从框架实现代码学习selenium让你事半功倍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。