python reptile selenium

Ready to work

A: install Google Chrome

Two: According to the version number of your browser to download the ChromeDriver (author of the version number is 76.0.3809.100)

ChromeDriver Download

I downloaded version

Three: the environment variable configuration

Under Script directory (under windows) simply copy the executable file to the python ChromDriver

Four: Verify the installation

Executed directly in cmd chromedrivercommand

Figure


1.selenium basic use

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://www.baidu.com')
input_ = browser.find_element_by_id('kw')
input_.send_keys('Python')
browser.close()

2. Object Browser reputation

from selenium import  webdriver

browser = webdriver.Chrome()
browser = webdriver.Firefox()
browser = webdriver.Edge()
browser = webdriver.PhantomJS()
browser = webdriver.Safari()

3. Access page

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
print(browser.page_source)
browser.close()

4. Find node

  • A single node
from selenium import webdriver
# 查找节点
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input_first = browser.find_element_by_id('q')
# input_first_1 = browser.find_element(By.ID, 'q')

input_second = browser.find_element_by_css_selector('#q')
input_third = browser.find_element_by_xpath('//*[@id="q"]')
print(input_first, input_second, input_third, sep='\n')
browser.close()
  • Method of obtaining a single node
find_element_by_id()
find_element_by_name()
find_element_by_xpath()
find_element_by_link_text()
find_element_by_partial_link_text()
find_element_by_tag_name()
find_element_by_class_name()
find_element_by_css_selector()

find_element()  #通用方法
需要传入两个参数
如:
find_element_by_id == find_element(By.ID, id)
  • A plurality of nodes
from selenium import webdriver

browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
lis = browser.find_elements_by_css_selector('.service-bd li')
print(lis)
browser.close()

#在单节点的基础上,element 加一个 s

5 node interaction

from selenium import webdriver
import time

browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
input_ = browser.find_element_by_id('q') 
input_.send_keys('跳蛛') #输入文字
time.sleep(1)   
input_.clear() # 清空文字
input_.send_keys('蜥蜴')
button = browser.find_element_by_class_name('btn-search')
button.click()

6 action chain

from selenium import webdriver
from  selenium.webdriver import ActionChains

browser = webdriver.Chrome()
url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'
browser.get(url)
browser.switch_to.frame('iframeResult')
source = browser.find_element_by_css_selector('#draggable')
target = browser.find_element_by_css_selector('#droppable')
actions = ActionChains(browser)
actions.drag_and_drop(source, target)
actions.perform()

Guess you like

Origin www.cnblogs.com/duoban/p/11366570.html