Python爬蟲之Selenium使用技巧
使用方法都寫在程序裏面的註釋中,請盡情享用,如果您覺得不錯可以點個贊哦🙂
代碼如下:
"""
<<WebDriver模塊常用方法>>
模塊方法: 含義:
1. set_window_size() 設置瀏覽器的大小
2. back() 控制瀏覽器後退
3. forward() 控制瀏覽器前進
4. refresh() 刷新當前頁面
5. clear() 清除文本
6. send_keys (value) 模擬按鍵輸入
7. click() 單擊元素
8. submit() 用於提交表單
9. get_attribute(name) 獲取元素屬性值
10. is_displayed() 設置該元素是否用戶可見
11. size 返回元素的尺寸
12. text 獲取元素的文本
<<定位元素>>
定位一個元素: 定位多個元素: 含義:
1. find_element_by_id find_elements_by_id 通過元素id定位
2. find_element_by_name find_elements_by_name 通過元素name定位
3. find_element_by_xpath find_elements_by_xpath 通過xpath表達式定位
4. find_element_by_link_text find_elements_by_link_tex 通過完整超鏈接定位
5. find_element_by_partial_link_text find_elements_by_partial_link_text 通過部分鏈接定位
6. find_element_by_tag_name find_elements_by_tag_name 通過標籤定位
7. find_element_by_class_name find_elements_by_class_name 通過類名進行定位
8. find_elements_by_css_selector find_elements_by_css_selector 通過css選擇器進行定位
<<等待條件函數>>
等待條件: 含義:
1. title_is 標題是某內容
2. title_contains 標題包含某內容
3. presence_of_element_located 節點加載出來,傳入定位元組,如(By.ID, 'p')
4. presence_of_all_elements_located 所有節點加載出來
5. visibility_of_element_located 節點可見,傳入定位元組
6. visibility_of 可見,傳入節點對象
7. text_to_be_present_in_element 某個節點文本包含某文字
8. text_to_be_present_in_element_value 某個節點值包含某文字
9. frame_to_be_available_and_switch_to_it 加載並切換
10. invisibility_of_element_located 節點不可見
11. alert_is_present 是否出現警告
12. element_to_be_clickable 節點可點擊
13. element_to_be_selected 節點可選擇,傳入節點對象
14. element_located_to_be_selected 節點可選擇,傳入定位元組
15. element_selection_state_to_be 傳入節點對象以及狀態,相等返回True,否則返回False
16. element_located_selection_state_to_be 傳入定位元組以及狀態,相等返回True,否則返回False
17. staleness_of 判斷一個節點是否仍在DOM,可判斷當前頁面是否已經刷新
<<Chrome瀏覽器配置選項>>
================================================================================================================
# 實例化配置選項
chrome_options = webdriver.ChromeOptions()
# 不加載圖片,加快訪問速度
chrome_options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})
# 設置爲開發者模式,避免被識別
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
# 設置無界面模式
chrome_options.add_argument('--headless')
# 設置默認編碼爲utf-8
options.add_argument('lang=zh_CN.UTF-8')
# 通過設置user-agent,用來模擬移動設備
<模擬 Android QQ瀏覽器>
options.add_argument('user-agent="MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"')
<模擬iPhone 6>
options.add_argument('user-agent="Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"')
# 設置selenium窗口大小
browser.set_window_size(configure.windowHeight, configure.windowWidth) # configure爲桌面分辨率實際大小
# 阻止密碼保存提示框的彈出
prefs = {}
prefs[“credentials_enable_service”] = False
prefs[“profile.password_manager_enabled”] = False
options.add_experimental_option(“prefs”, prefs)
# 添加應用擴展程序 (.crx文件)
extension_path = 'D:/extension/XPath-Helper_v2.0.2.crx'
chrome_options.add_extension(extension_path)
# 啓動配置選項
self.driver = webdriver.Chrome(options=chrome_options)
================================================================================================================
"""
# -*- coding:utf-8 -*-
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
__author__ = 'Evan'
class Crawler(object):
def __init__(self, url=''):
"""
Chrome常用配置選項:
1. 不加載圖片,加快訪問速度
2. 設置爲開發者模式,避免被識別
3. 設置無界面模式
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
chrome_options.add_argument('--headless')
self.driver = webdriver.Chrome(options=chrome_options)
=============================================================
# PhantomJS設置緩存和禁用圖片加載
service_args = ['--load-images=false', '--disk-cache=true']
self.driver = webdriver.PhantomJS(service_args=service_args)
"""
self.source_url = url
self.driver = webdriver.Chrome() # 選擇瀏覽器驅動
self.waiting = WebDriverWait(self.driver, 30) # 設置顯示等待30秒
self.driver.implicitly_wait(30) # 設置隱示等待30秒
self.actions = webdriver.ActionChains(self.driver) # 動作鏈初始化
def switch_to_windows(self, to_parent_windows=False):
"""
切換到不同的windows窗口
:param to_parent_windows: 默認爲False,如果設置爲True則回到主窗口
:return:
"""
total = self.driver.window_handles
if to_parent_windows:
self.driver.switch_to.window(total[0])
else:
current_windows = self.driver.current_window_handle
for window in total:
if window != current_windows:
self.driver.switch_to.window(window)
def switch_to_frame(self, index=0, to_parent_frame=False, to_default_frame=False):
"""
切換到不同的frame框架
:param index: expect by frame index value or id or name or element
:param to_parent_frame: 默認爲False,如果設置爲True則切換到上一個frame框架
:param to_default_frame: 默認爲False,如果設置爲True則切換到最上層的frame框架
:return:
"""
if to_parent_frame:
self.driver.switch_to.parent_frame()
elif to_default_frame:
self.driver.switch_to.default_content()
else:
self.driver.switch_to.frame(index)
def open_new_windows(self, new_url=''):
"""
打開一個新的windows窗口
:param new_url: 新的URL
:return:
"""
js = "window.open({})".format(new_url)
self.driver.execute_script(js)
time.sleep(2)
def page_scrolling(self, go_to_bottom=False, rolling_distance=(0, 1000)):
"""
頁面滾動,如果沒有滾動效果,添加延時(頁面需要全部加載完畢才能滾動)
:param bool go_to_bottom: 默認爲False,如果爲True則滾動到當前頁面的最底部
:param tuple rolling_distance: 滾動距離,默認是向下滾動1000像素
:return:
"""
time.sleep(5)
if go_to_bottom:
js = "window.scrollTo(0, document.body.scrollHeight)"
else:
js = "window.scrollBy({}, {})".format(rolling_distance[0], rolling_distance[1])
self.driver.execute_script(js)
def screen_shot(self, picture_name='example.jpg'):
"""
截取當前網頁並保存爲圖片
:param picture_name: 保存的圖片名稱
:return:
"""
self.driver.save_screenshot(picture_name)
def action_chain(self, source, target):
"""
執行鼠標拖曳
:param source: 拖曳前位置
:param target: 拖曳後位置
:return:
"""
self.actions.drag_and_drop(source, target)
self.actions.perform()
def close_current_windows(self):
# 關閉當前頁面
if self.driver:
self.driver.close()
def quit_browser(self):
# 退出所有頁面
if self.driver:
self.driver.quit()
def main(self):
# 訪問頁面
self.driver.get(self.source_url)
# 定位節點
self.driver.find_element_by_xpath('//*[@id="kw"]') # 通過xpath定位
input_box = self.waiting.until(EC.presence_of_element_located((By.XPATH, '//*[@id="kw"]'))) # 通過等待條件定位
# 獲取節點信息
print(input_box.get_attribute('class')) # 獲取節點的class屬性值
print(input_box.id) # 獲取節點的id值
print(input_box.text) # 獲取節點的文本值
print(input_box.location) # 獲取節點在頁面中的相對位置
print(input_box.tag_name) # 獲取節點的標籤名稱
print(input_box.size) # 獲取節點的大小
# 獲取網頁信息
print(self.driver.current_url) # 獲取當前的URL
print(self.driver.get_cookies()) # 獲取當前的Cookies
print(self.driver.page_source) # 獲取網頁源代碼
# 節點交互
input_box.clear() # 清空文本
input_box.send_keys('python') # 輸入文本
input_box.send_keys(Keys.ENTER) # 執行輸入
# 網頁交互
self.driver.back() # 網頁後退
time.sleep(1)
self.driver.forward() # 網頁前進
# 滾動頁面
self.page_scrolling() # 執行javascript
# 動作鏈
source = self.driver.find_element_by_xpath('//*[@id="result_logo"]/img[1]')
target = self.driver.find_element_by_xpath('//*[@id="kw"]')
self.action_chain(source=source, target=target) # 鼠標拖曳
if __name__ == '__main__':
crawler = Crawler(url='https://www.baidu.com')
crawler.main()