Python + Selenium notes (1): Environment configuration + simple example, pythonselenium
# Environment configuration based on windows OS
# Learning selenium requires some basics of HTML and xpth. It is not recommended that you take some time to learn the basics (otherwise, element positioning, especially xpth may look a bit tricky)
# HTML: http://www.runoob.com/html/ # xpth: http://www.runoob.com/xpath
(1)Environment Configuration
(1) execute the following command (prerequisite: You have installed the python environment. Refer to the python notes (1 ))
Pip install-U selenium
(2) http://docs.seleniumhq.org/download/ (if the Website Cannot open the FQ)
Download Mozilla GeckoDriver (because I am using Firefox for testing, download this), decompress the package, and put it in any directory, then add the decompressed path to the system variable path (I tried it on two computers, one in any directory and the other in the python installation directory, which can be used anyway .)
(3) If an error is still reported after the browser driver instance is created (this may be due to the browser version problem. If python3.6 + selenium3.9 + Firefox 47 + Mozilla GeckoDriverV0.19.1, the error will be reported)
(2)Simple Example
#Import webdriver
FromSeleniumImportWebdriver
# FirefoxBinary --Location of the binary file to be imported
FromSelenium. webdriver. firefox. firefox_binaryImportFirefoxBinary
#Specify the binary path of Firefox
Firefox = FirefoxBinary (R "C: \ Program Files (x86) \ MozillaFirefox \ firefox.exe")
Driver = webdriver. Firefox (firefox_binary = firefox)#Create a Firefox driver instance
Driver. implicitly_wait (2)#Set the wait time (define the timeout time for executing the step)
Driver. maximize_window ()#Maximize browsers
Driver. get ("Https://www.cnblogs.com /")#Open the blog Home Page
Search_field = driver. find_element_by_id ('Zzk _ Q')#Use id to locate the search box on the blog homepage
Search_btn = driver. find_element_by_class_name ('Search _ btn')#Use class to locate the query button on the blog homepage
Search_field.clear ()#Clear the value of the search box (if any)
Search_field.send_keys ("Python")#Enter query conditions in the search box
Search_btn.click ()#Click Search
# Search_field.submit ()
# Select a value between Products = driver. find_elements_by_xpath ('// H3 [a/@ target = "_ blank"]/')
#Iteration list products, output text value
ForPInProducts:
Print (p. text)
#Select the value of the <a target = "_ blank"> node and return a list
Pro = driver. find_elements_by_xpath ('// H3/a [@ target = "_ blank"]')
#Value of href attribute output by Iteration
ForPInPro:
Print (p. get_attribute ('Href'))
#Close your browser
Driver. quit ()
(3)Output:
In the second step, xpth mainly locates the following