Selenium瀏覽器自動化測試工具
目錄
Selenium 是一個用於Web應用程序測試的工具。Selenium測試直接運行在瀏覽器中,就像真正的用戶在操作一樣。
支持的瀏覽器包括IE(7, 8, 9, 10, 11),Mozilla Firefox,Safari,Google Chrome,Opera等。這個工具的主要功能包括:
測試與瀏覽器的兼容性——測試你的應用程序看是否能夠很好得工作在不同瀏覽器和操作系統之上。
測試系統功能——創建回歸測試檢驗軟件功能和用戶需求。支持自動錄制動作和自動生成 .Net、Java、Perl等不同語言的測試腳本。
Selenium模塊在爬蟲中的使用
- selenium模塊在爬蟲中的使用
- 概念:是一個基於瀏覽器自動化的模塊。
- 爬蟲之間的關聯:
- 便捷的捕獲到動態加載到的數據。(可見即可得)
- 實現模擬登陸
- 環境安裝:pip install selenium
- 基本使用:
- 准備好某一款瀏覽器的驅動程序:http://chromedriver.storage.googleapis.com/index.html
- 版本的映射關系:https://blog.csdn.net/huilan_same/article/details/51896672
- 實例化某一款瀏覽器對象
- 動作鏈:
- 一系列連續的動作
- 在實現標簽定位時,如果發現定位的標簽是存在於iframe標簽之中的,則在定位時必須執行一個
固定的操作:bro.switch_to.frame('id')
- 無頭瀏覽器的操作:無可視化界面的瀏覽器
- PhantomJs:停止更新
- 谷歌無頭瀏覽器
- 讓selenium規避檢測
Python簡單使用Selenium
from time import sleep
from selenium import webdriver
# 后面是你的瀏覽器驅動位置,記得前面加r'','r'是防止字符轉義的
driver = webdriver.Chrome(r'chromedriver.exe')
# 用get打開百度頁面
driver.get("http://www.baidu.com")
# 查找頁面的“設置”選項,並進行點擊
driver.find_elements_by_link_text('設置')[0].click()
sleep(2)
# # 打開設置后找到“搜索設置”選項,設置為每頁顯示50條
driver.find_elements_by_link_text('搜索設置')[0].click()
sleep(2)
# 選中每頁顯示50條
m = driver.find_element_by_id('nr')
sleep(2)
m.find_element_by_xpath('//*[@id="nr"]/option[3]').click()
m.find_element_by_xpath('.//option[3]').click()
sleep(2)
# 點擊保存設置
driver.find_elements_by_class_name("prefpanelgo")[0].click()
sleep(2)
# 處理彈出的警告頁面 確定accept() 和 取消dismiss()
driver.switch_to_alert().accept()
sleep(2)
# 找到百度的輸入框,並輸入 美女
driver.find_element_by_id('kw').send_keys('美女')
sleep(2)
# 點擊搜索按鈕
driver.find_element_by_id('su').click()
sleep(2)
# 在打開的頁面中找到“Selenium - 開源中國社區”,並打開這個頁面
driver.find_elements_by_link_text('美女_百度圖片')[0].click()
sleep(3)
# 關閉瀏覽器
driver.quit()
-
執行結果
https://img2018.cnblogs.com/blog/1644071/201909/1644071-20190917200511373-329204956.gif
Selenium的基本操作
from selenium import webdriver
from time import sleep
bro = webdriver.Chrome(executable_path='chromedriver.exe')
bro.get('https://www.jd.com/')
sleep(1)
#進行標簽定位
search_input = bro.find_element_by_id('key')
search_input.send_keys('mac pro')
btn = bro.find_element_by_xpath('//*[@id="search"]/div/div[2]/button')
btn.click()
sleep(2)
#執行js
bro.execute_script('window.scrollTo(0,document.body.scrollHeight)')
sleep(2)
page_text = bro.page_source
print(page_text)
sleep(2)
bro.quit()
Selenium爬取動態加載的數據
#便捷的捕獲到動態加載到的數據。(可見即可得)
from selenium import webdriver
from time import sleep
from lxml import etree
bro = webdriver.Chrome(executable_path='chromedriver.exe')
bro.get('http://125.35.6.84:81/xk/')
sleep(1)
page_text = bro.page_source
page_text_list = [page_text]
for i in range(3):
bro.find_element_by_id('pageIto_next').click()#點擊下一頁
sleep(1)
page_text_list.append(bro.page_source)
for page_text in page_text_list:
tree = etree.HTML(page_text)
li_list = tree.xpath('//ul[@id="gzlist"]/li')
for li in li_list:
title = li.xpath('./dl/@title')[0]
num = li.xpath('./ol/@title')[0]
print(title+':'+num)
sleep(2)
bro.quit()
#執行結果
江蘇正東生物科技有限公司:蘇妝20160159
吉林正德葯業有限公司:吉妝20160011
湖北潛江制葯股份有限公司:鄂妝20190003
深圳市發康堂中醫葯研究有限公司:粵妝20180101
洞瑪生物技術(深圳)有限公司:粵妝20160644
領先(中國)生物科技有限公司:閩妝20170030
普洱聯眾生物資源開發有限公司:雲妝20160023
珠海市富康源旅游用品有限公司:粵妝20180248
廣州康又美化妝品有限公司:粵妝20160830
江蘇西宏生物醫葯有限公司:蘇妝20190023
廣州市大研生物技術有限公司:粵妝20161133
廣州玖宮研化生物科技有限公司:粵妝20160438
......省略
Selenium動作鏈 (實現拖動操作)
"""
動作鏈:
- 一系列連續的動作
- 在實現標簽定位時,如果發現定位的標簽是存在於iframe標簽之中的,則在定位時必須執行一個
"""
from selenium import webdriver
from time import sleep
from selenium.webdriver import ActionChains
bro = webdriver.Chrome(executable_path='chromedriver.exe')
bro.get('https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
bro.switch_to.frame('iframeResult')
div_tag = bro.find_element_by_id('draggable')
#拖動= 點擊+滑動
action = ActionChains(bro)
action.click_and_hold(div_tag)
for i in range(5):
#perform讓動作鏈立即執行
action.move_by_offset(17,5).perform()
sleep(0.5)
action.release()
sleep(3)
bro.quit()
Selenium使用谷歌無頭瀏覽器 示例
#使用谷歌無頭瀏覽器
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(r'chromedriver.exe',chrome_options=chrome_options)
driver.get('https://www.cnblogs.com/')
print(driver.page_source)
#執行結果
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn">
<head><script src="https://securepubads.g.doubleclick.net/gpt/pubads_impl_rendering_2019091201.js">
</script><script async="" src="https://www.google-analytics.com/analytics.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="referrer" content="always" />
<title>博客園 - 開發者的網上家園</title>
.......................省略.......................
滬公網安備 31011502001144號</span></a></div>
</div>
</div>
</body>
</html>
Selenium設置代理
from time import sleep
from selenium import webdriver
# 設置代理
options = webdriver.ChromeOptions()
proxy = f"--proxy-server=https://{'113.74.61.232:28803'}"
options.add_argument(proxy)
# 導入瀏覽器驅動
web = webdriver.Chrome(r'chromedriver.exe',options=options)
# 訪問指定頁面
web.get('https://www.baidu.com/s?ie=UTF-8&wd=ip')
sleep(5)
web.close()
規避Selenium被檢測
#如何規避selenium被檢測
from selenium import webdriver
from selenium.webdriver import ChromeOptions
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = webdriver.Chrome(r'chromedriver.exe',options=option)
driver.get('https://www.taobao.com/')

