seleniumでよく使われる構文
3221 ワード
転載先:https://blog.csdn.net/topleeyap/article/details/79049147
# !/usr/bin/env python
# -*- coding:utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver import ActionChains
# WebDriver
# driver=webdriver.Firefox()
# driver=webdriver.Chrome()
# driver=webdriver.PhantomJS()
#
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36")
driver = webdriver.PhantomJS(desired_capabilities=dcap)
# Cookie
# cookie
cookies={
'username':'xxx',
'password':'xxx'
}
driver.add_cookie(cookie_dict=cookies)
driver.get('http://example.com')
# cookie
driver.get_cookies()
# GET ( )
driver.get('https://www.sogou.com/')
# URL
url=driver.current_url
# HTML
source=driver.page_source
#
driver.refresh()
#
driver.save_screenshot('sougou.png')
#
driver.forward()
#
driver.back()
#
driver.maximize_window()
# ( , )
# driver.close()
#
# driver.quit()
#
#
# ,by ,value
# By.ID
# By.CLASS_NAME
# By.XPATH
# By.CSS_SELECTOR
# By.LINK_TEXT
# By.PARTIAL_LINK_TEXT
# By.NAME
# By.TAG_NAME
element=driver.find_element(by=By.ID,value='id')
#
element = driver.find_element_by_id('id')
element=driver.find_element_by_class_name('class')
element=driver.find_element_by_xpath('xpath')
element=driver.find_element_by_css_selector('css_selector')
element=driver.find_element_by_link_text('link_text') #
element=driver.find_element_by_partial_link_text('partial_link_text') #
element=driver.find_element_by_name('name') # name
element=driver.find_element_by_tag_name('tag_name') #
# ( , list)
#
elements=driver.find_elements(by=By.XPATH,value='xpath')
#
elements=driver.find_elements_by_id('id')
#
element.clear()
#
element.send_keys('Python')
#
element.send_keys(Keys.RETURN)
# ( element )
element.click()
#
alert_ele=driver.switch_to.alert
alert_ele.dismiss()
# ActionChains( )
source_element=driver.find_element(By.ID,'id')
target_element=driver.find_element(By.ID,'id')
action_chains=ActionChains(driver)
action_chains.drag_and_drop(source=source_element,target=target_element).perform()
# , :
driver.set_page_load_timeout(30)
#
# : , :
driver.implicitly_wait(5)
# :
import time
time.sleep(5)
# :
try:
element=WebDriverWait(driver,timeout=10).until(
EC.presence_of_all_elements_located((By.ID,'id'))
)
finally:
driver.quit()
# JS
js='window.scrollTo(0,document.body.scrollHeight);' #
driver.execute_script(js)
time.sleep(3)