Looking at problems from a fresh perspective: analyzing selenium principle from the perspective of Python

Software testing 2021-10-29 07:06:17
looking problems fresh perspective analyzing

 Insert picture description here

Selenium Workflow

 Insert picture description here
Selenium working principle

The client and server are actually connected through http Protocol to communicate , The interface document of the server can be referred to :

https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol#sessionsessionidelement

The client passes in the request mode according to the requirements of the server interface 、 request url And request data , And then send http request , After receiving the request, the server drives the browser to execute the command .

selenium Actually, the request functions of various operation interfaces have been encapsulated , Users only need to pass in data through the specified method .

Such as get、click、find_element It actually encapsulates the whole http Method of request process .

That is, the tester only needs to call the corresponding method according to the functional requirements and pass the parameters , In the end by the selenium After assembling the request information, send the request .

so , You can skip it selenium, By myself requests The module build request information is sent to the driver , So as to drive the browser to perform relevant operations .

From the perspective of source code Selenium principle

explain

Following example , With Python、Chrome The driver 、Chrome Browser expansion instructions .

adopt Selenium Implement workflow

# start-up chrome browser
driver = webdriver.Chrome()
# Visit Baidu website
driver.get("http://www.baidu.com")
# Find the input box element
ele = driver.find_element_by_id("kw")
# Enter in the input box “selenium”
ele.send_keys("selenium")
# Find Baidu button
ele = driver.find_element_by_id("su")
# Click Baidu button
ele.click()

Selenium The source code parsing

① driver = webdriver.Chrome()

start-up chromedriver The driver , After starting, it can pass http://ip:port Access driver .

 picture

adopt execute Method , structure “ Create a new session ” Interface request information , And send the http request , Return to session id.

Request mode :POST

Request address :http://localhost:post/session

Request data :

data = {"desiredCapabilities":{
"browserName": "chrome",
"version":"85.0.4183.83",
"platform":"WINDOWS"}
}

 Insert picture description here

 picture

 picture

② driver.get(“http://www.baidu.com”)

adopt execute Method , Press get Command interface information construction http Request information , And send the http request .

Request mode :POST

Request address :http://localhost:post/session/$sessionId/url(sessionId For session id, from ① In order to get )

Request data :

{"url": "http://www.baidu.com"}

 Insert picture description here

 picture

③ driver.find_element_by_id(“kw”)

adopt execute Method , Press find_element_by_id Command interface information construction http Request information , And send the http request .

Request mode :POST

Request address :http://localhost:post/session/$sessionId/element(sessionId For session id, from ① In order to get )

Request data :

{"using":"id","value":"kw"}

 Insert picture description here

 picture

 picture

④ ele.send_keys(“selenium”)

adopt execute Method , Press send_keys Command interface information construction http Request information , And send the http request .

Request mode :POST

Request address :http://localhost:post/session/ s e s s i o n I d / e l e m e n t / sessionId/element/ sessionId/element/id/value(sessionId For session id, from ① In order to get ,id For the elements id, from ③ obtain )

Request data :

{"value": ["selenium"]}

 Insert picture description here

 picture

 picture

⑤ ele.click()

adopt execute Method , Press click Command interface information construction http Request information , And send the http request .

Request mode :POST

Request address :http://localhost:post/session/ s e s s i o n I d / e l e m e n t / sessionId/element/ sessionId/element/id/click(sessionId For session id, from ① In order to get ,id For the elements id, from ③ obtain )

Request data : nothing

 picture

 picture

 picture

adopt requests Module operation verification

Code implementation

 # TODO Access to the domain name
base_url = "http://localhost:9515"
# TODO Create a session
url = base_url + "/session"
data = {
"desiredCapabilities":{
"browserName": "chrome",
"version":"85.0.4183.83",
"platform":"WINDOWS"
}
}
res = request("POST",url,json=data)
session_id = res.json()["sessionId"] # Return to session id
sleep(2)
# TODO send out get command - Visit a website
url = base_url + "/session/{}/url".format(session_id)
data = {
"url": "http://www.baidu.com"
}
res = request("POST",url,json=data)
# TODO send out find_element command - Look for the element
url = base_url + "/session/{}/element".format(session_id)
data = {
"using":"id",
"value":"kw"
}
res = request("POST",url,json=data)
ele = jsonpath(res.json(),"$..ELEMENT")[0] # Returns the element id
# TODO send out send_keys command - Input content
url = base_url + "/session/{}/element/{}/value".format(session_id,ele)
data = {
"value": ["selenium"]
}
res = request("POST",url,json=data)
# TODO send out find_element command - Look for the element
url = base_url + "/session/{}/element".format(session_id)
data = {
"using":"id",
"value":"su"
}
res = request("POST",url,json=data)
ele = jsonpath(res.json(),"$..ELEMENT")[0] # Returns the element id
# TODO send out click command - Element click
url = base_url + "/session/{}/element/{}/click".format(session_id,ele)
res = request("POST",url)

Running results

 Insert picture description here

 Insert picture description here

Last : It can be in the official account : Sad spicy bar ! Get a free copy of 216 Page software testing engineer interview guide document information . And the corresponding video learning tutorial is free to share !, It includes basic knowledge 、Linux necessary 、Shell、 The principles of the Internet 、Mysql database 、 Special topic of bag capturing tools 、 Interface testing tool 、 Test advanced -Python Programming 、Web automated testing 、APP automated testing 、 Interface automation testing 、 Testing advanced continuous integration 、 Test architecture development test framework 、 Performance testing 、 Safety test, etc. .

If my blog helps you 、 If you like my blog content , please “ give the thumbs-up ” “ Comment on ” “ Collection ” One button, three links ! Friends who like software testing , You can join our testing technology exchange group :914172719( There are various software testing resources and technical discussions )


Good article recommends

Job transfer interview , Job hopping interview , These interview skills that software testers must know !

Interview : First tier cities move bricks ! Another software testing post ,5000 That's enough …

interviewer : Work for three years , And a preliminary test ? I'm afraid the title of your software test engineer should be enclosed in double quotation marks …

What kind of person is suitable for software testing ?

The man who leaves work on time , Promoted before me …

The test post changes jobs repeatedly , Jump, jump and disappear …

版权声明
本文为[Software testing]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/10/20211013184031899p.html

  1. Python,前缀后缀相同时合并
  2. 关于#python#的问题:python
  3. 關於#python#的問題:python
  4. Python,前綴後綴相同時合並
  5. Questions sur # # Python #: Python
  6. Python, préfixe et suffixe combinés en même temps
  7. python manage.py shell无法运行,
  8. python manage.py shell無法運行,
  9. Le shell Python manage.py ne fonctionne pas,
  10. python中使用vscode Import 'matplotlib.pyplot' could not be resolved from source 问题
  11. [Chapter 11 of the full version] Python advanced crawler practice - system master Po anti climbing skills challenge high salary
  12. L'utilisation de vscode Import 'matplotlib.pyplot' en python ne peut pas être résolue à partir du problème source
  13. Python fusionne les deux listes et supprime les éléments dupliqués lors de la fusion
  14. [JS Reverse AES Reverse Encryption] python crawler combat, les jours sont de plus en plus décisifs
  15. 30 jeux Python. Je peux jouer à la pêche au travail pendant une journée.
  16. J'a i collecté un nouveau hit de liste en python, donc c'est un secret que quelqu'un d'autre peut devenir un magnat des médias!
  17. J'a i utilisé Python pour ramper à travers 5000 belles photos de papier peint, un jour oublié Premier amour!
  18. [Python planting system] the best green plant for your girlfriend. Girls love it when they see it! Attachment: should be able to feed - right??!
  19. [Python love guide] two small programs for sweetness burst table are released! Afraid you can't find someone?
  20. J'ai utilisé Python pour ramper 1000 lettres d'amour pour aider mon colocataire à exprimer les fleurs de classe, mais les inverser et les inverser... C'est le secret ultime des fleurs de classe!
  21. J'ai utilisé Python pour me connecter à la plus grande plate - forme de jeu au monde, et à quel point le cryptage steam est intelligent [code source inclus]
  22. python中列表转为矩阵后无法进行矩阵的乘法运算
  23. Python crawler Development and Learning full tutoriel 2nd Edition, banggan 100000 words [recommended Collection]
  24. Python crawler haut de gamme: microstore confus anti - décryptage
  25. La multiplication de la matrice ne peut pas être effectuée lorsque la liste est convertie en matrice en python
  26. Introduction to operators in python (Part 1)
  27. Are the dictionaries in Python ordered
  28. Introduction to dictionaries in Python
  29. List introduction in Python
  30. pandas比较两个dataframe特定数据列的数值是否相同并给出差值:使用np.where函数
  31. Python使用matplotlib绘制透明背景的可视化图像并保存透明背景的可视化结果(transparent background)
  32. Python self study notes -- basic grammar
  33. Python utilise matplotlib pour dessiner une image visuelle de l'arrière - plan transparent et enregistrer les résultats visuels de l'arrière - plan transparent
  34. Pandas compare les valeurs de deux colonnes de données spécifiques à dataframe et donne des valeurs de voyage: en utilisant la fonction np.where
  35. Comment configurer une application ASGI Django avec Postgres, nginx et uvicorn sur Ubuntu 20.04
  36. What are the advantages of Python and how to get started quickly
  37. Python self study notes -- basic data types
  38. Python code reading (Chapter 14): List Union
  39. Analyse statistique de la fonction de données des essais aléatoires Python
  40. Alien invasion project in Python application -- Aliens (Part 2)
  41. Python code reading (Chapter 14): List Union
  42. Lecture du Code Python (article 25): diviser les chaînes multilignes en listes
  43. Python self study notes -- operators
  44. Formation python - différences entre http et HTTPS
  45. Implementation of automatic timing comment function on Python CSDN platform
  46. python+tkinter+treeview子控件快捷键
  47. Raccourcis clavier pour les sous - contrôles Python + tkinter + treeview
  48. Analyse des données Python
  49. python+tkinter+treeview子控件快捷鍵
  50. Devine si je peux attraper Maotai avec la programmation python? Tout est ouvert à github
  51. À propos de pygame.display.set in Python Un petit problème avec mode ()
  52. Implementation of automatic timing comment function on Python CSDN platform
  53. python:dataframe进行iteritem遍历时如何将输出结果按照列分别输出为该列最后一行
  54. python:dataframe進行iteritem遍曆時如何將輸出結果按照列分別輸出為該列最後一行
  55. Python: comment le dataframe affiche les résultats de sortie par colonne à la dernière ligne de la colonne lors de la traversée de l'itemitem
  56. Écrivez un gadget de bureau pour votre fille préférée en python et elle dit que c'est génial!
  57. Introduction to closures in Python 3
  58. Global / nonlocal usage in Python 3
  59. Introduction to context manager in Python 3
  60. Common standard library random, python introductory tutorial 5 or 6 questions a day | Python skill tree