Python-Selenium自動(dòng)化爬蟲
簡單介紹:
Selenium
是一個(gè)Web的自動(dòng)化測試工具,最初是為網(wǎng)站自動(dòng)化測試而開發(fā)的,Selenium 可以直接運(yùn)行在瀏覽器上,它支持所有主流的瀏覽器(包括PhantomJS這些無界面的瀏覽器(2018年開發(fā)者說暫停開發(fā),chromedriver也可以實(shí)現(xiàn)同樣的功能)),可以接收指令,讓瀏覽器自動(dòng)加載頁面,獲取需要的數(shù)據(jù),甚至頁面截屏。
1.安裝
pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple
2.下載瀏覽器驅(qū)動(dòng)
這里用的谷歌瀏覽器
http://npm.taobao.org/mirrors/chromedriver/
查看自己的瀏覽器版本下載對(duì)應(yīng)的驅(qū)動(dòng)。
把解壓后的驅(qū)動(dòng)放在自己的python.exe
目錄下。
3.實(shí)例
3.1下載對(duì)應(yīng)版本的瀏覽器驅(qū)動(dòng)
http://npm.taobao.org/mirrors/chromedriver/
把解壓后的驅(qū)動(dòng)放在自己的python.exe 目錄下
3.2測試code,打開一個(gè)網(wǎng)頁,并獲取網(wǎng)頁的標(biāo)題
from selenium.webdriver import Chrome if __name__ == '__main__': ? ? web = Chrome() ? ? web.get("https://baidu.com") ? ? print(web.title)
3.3一個(gè)小樣例
from selenium.webdriver import Chrome if __name__ == '__main__': ? ? web = Chrome() ? ? url = 'https://ac.nowcoder.com/acm/home' ? ? web.get(url) ?? ?# 獲取要點(diǎn)擊的a標(biāo)簽 ? ? el = web.find_element_by_xpath('/html/body/div/div[3]/div[1]/div[1]/div[1]/div/a') ?? ?# 點(diǎn)擊 ? ? el.click() ? ? ? ? ? ? ? ? ? ? ? ? ?# "/html/body/div/div[3]/div[1]/div[2]/div[2]/div[2]/div[1]/h4/a" ? ? # 爬取想要的內(nèi)容 ? ? lists = web.find_elements_by_xpath("/html/body/div/div[3]/div[1]/div[2]/div[@class='platform-item js-item ']/div[" ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"2]/div[1]/h4/a") ? ? print(len(lists)) ? ? for i in lists: ? ? ? ? print(i.text)
3.4自動(dòng)輸入并跳轉(zhuǎn)
from selenium.webdriver import Chrome from selenium.webdriver.common.keys import Keys import time if __name__ == '__main__': ? ? web = Chrome() ? ? url = 'https://ac.nowcoder.com/acm/home' ? ? web.get(url) ? ? el = web.find_element_by_xpath('/html/body/div/div[3]/div[1]/div[1]/div[1]/div/a') ? ? el.click() ? ? time.sleep(1) ? ? input_el = web.find_element_by_xpath('/html/body/div/div[3]/div[1]/div[1]/div[1]/form/input[1]') ? ? input_el.send_keys('???, Keys.ENTER) ? ? # do something
4.開啟無頭模式
是否開啟無頭模式(即是否需要界面)
from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options option = Options() ?# 實(shí)例化option對(duì)象 option.add_argument("--headless") ?# 給option對(duì)象添加無頭參數(shù) if __name__ == '__main__': ? ? web = Chrome(executable_path='D:\PyProject\spider\venv\Scripts\chromedriver.exe',options=option) # 指定驅(qū)動(dòng)位置,否則從python解釋器目錄下查找. ? ? web.get("https://baidu.com") ? ? print(web.title)
5.保存頁面截圖
from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options option = Options() ?# 實(shí)例化option對(duì)象 option.add_argument("--headless") ?# 給option對(duì)象添加無頭參數(shù) if __name__ == '__main__': ? ? web = Chrome() ? ? web.maximize_window() ?# 瀏覽器窗口最大化 ? ? web.get("https://baidu.com") ? ? print(web.title) ? ? web.save_screenshot('baidu.png') ?# 保存當(dāng)前網(wǎng)頁的截圖 ?保存到當(dāng)前文件夾下 ? ? web.close() ?# 關(guān)閉當(dāng)前網(wǎng)頁
6.模擬輸入和點(diǎn)擊
from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options option = Options() ?# 實(shí)例化option對(duì)象 option.add_argument("--headless") ?# 給option對(duì)象添加無頭參數(shù) if __name__ == '__main__': ? ? web = Chrome() ? ? web.maximize_window() ?# 瀏覽器窗口最大化 ? ? web.get("https://baidu.com") ? ? el = web.find_element_by_id('kw') ? ? el.send_keys('Harris-H') ? ? btn = web.find_element_by_id('su') ? ? btn.click() ? ? # web.close() ?# 關(guān)閉當(dāng)前網(wǎng)頁
貌似現(xiàn)在百度可以識(shí)別出selenium
,還需要圖片驗(yàn)證。
6.1根據(jù)文本值查找節(jié)點(diǎn)
# 找到文本值為百度一下的節(jié)點(diǎn) driver.find_element_by_link_text("百度一下")? # 根據(jù)鏈接包含的文本獲取元素列表,模糊匹配 driver.find_elements_by_partial_link_text("度一下")?
6.2獲取當(dāng)前節(jié)點(diǎn)的文本
ele.text # 獲取當(dāng)前節(jié)點(diǎn)的文本 ele.get_attribute("data-click") ?# 獲取到屬性對(duì)應(yīng)的value
6.3打印當(dāng)前網(wǎng)頁的一些信息
print(driver.page_source) ?# 打印網(wǎng)頁的源碼 print(driver.get_cookies()) ?# 打印出網(wǎng)頁的cookie print(driver.current_url) ?# 打印出當(dāng)前網(wǎng)頁的url
6.4關(guān)閉瀏覽器driver.close() # 關(guān)閉當(dāng)前網(wǎng)頁
driver.close() # 關(guān)閉當(dāng)前網(wǎng)頁 driver.quit() # 直接關(guān)閉瀏覽器
6.5模擬鼠標(biāo)滾動(dòng)
from selenium.webdriver import Chrome import time if __name__ == '__main__': ? ? driver = Chrome() ? ? driver.get( ? ? ? ? "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=78000241_12_hao_pg&wd=selenium%20js%E6%BB%91%E5%8A%A8&fenlei=256&rsv_pq=8215ec3a00127601&rsv_t=a763fm%2F7SHtPeSVYKeWnxKwKBisdp%2FBe8pVsIapxTsrlUnas7%2F7Hoo6FnDp6WsslfyiRc3iKxP2s&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_sug3=31&rsv_sug1=17&rsv_sug7=100&rsv_sug2=0&rsv_btype=i&inputT=9266&rsv_sug4=9770") ? ? # ?1.滾動(dòng)到網(wǎng)頁底部 ? ? js = "document.documentElement.scrollTop=1000" ? ? # 執(zhí)行js ? ? driver.execute_script(js) ? ? time.sleep(2) ? ? # 滾動(dòng)到頂部 ? ? js = "document.documentElement.scrollTop=0" ? ? driver.execute_script(js) ?# 執(zhí)行js ? ? time.sleep(2) ? ? driver.close()
7.ChromeOptions
options = webdriver.ChromeOptions() options.add_argument("--proxy-server=http://110.52.235.176:9999") # 添加代理 options.add_argument("--headless") # 無頭模式 options.add_argument("--lang=en-US") # 網(wǎng)頁顯示英語 prefs = {"profile.managed_default_content_settings.images": 2, 'permissions.default.stylesheet': 2} # 禁止渲染 options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(executable_path="D:\ProgramApp\chromedriver\chromedriver73.exe",chrome_options=options) ? driver.get("http://httpbin.org/ip") ?
8.驗(yàn)證滑塊移動(dòng)
目標(biāo):滑動(dòng)驗(yàn)證碼
- 1.定位按鈕
- 2.按住滑塊
- 3.滑動(dòng)按鈕
import time from selenium import webdriver if __name__ == '__main__': ? ? chrome_obj = webdriver.Chrome() ? ? chrome_obj.get('https://www.helloweba.net/demo/2017/unlock/') ? ? # 1.定位滑動(dòng)按鈕 ? ? click_obj = chrome_obj.find_element_by_xpath('//div[@class="bar1 bar"]/div[@class="slide-to-unlock-handle"]') ? ? # 2.按住 ? ? # 創(chuàng)建一個(gè)動(dòng)作鏈對(duì)象,參數(shù)就是瀏覽器對(duì)象 ? ? action_obj = webdriver.ActionChains(chrome_obj) ? ? # 點(diǎn)擊并且按住,參數(shù)就是定位的按鈕 ? ? action_obj.click_and_hold(click_obj) ? ? # 得到它的寬高 ? ? size_ = click_obj.size ? ? width_ = 298 - size_['width'] ?# 滑框的寬度 減去 滑塊的 寬度 就是 向x軸移動(dòng)的距離(向右) ? ? print(width_) ? ? # 3.定位滑動(dòng)坐標(biāo) ? ? action_obj.move_by_offset(298-width_, 0).perform() ? ? # 4.松開滑動(dòng) ? ? action_obj.release() ? ? time.sleep(6) ? ? chrome_obj.quit()
9.打開多窗口和頁面切換
有時(shí)候窗口中有很多子tab頁面。這時(shí)候肯定是需要進(jìn)行切換的。selenium提供了一個(gè)叫做switch_to_window來進(jìn)行切換,具體切換到哪個(gè)頁面,可以從driver.window_handles
中找到
from selenium import webdriver if __name__ == '__main__': ? ? driver = webdriver.Chrome() ? ? driver.get("https://www.baidu.com/") ? ? driver.implicitly_wait(2) ? ? driver.execute_script("window.open('https://www.douban.com/')") ? ? driver.switch_to.window(driver.window_handles[1]) ? ? print(driver.page_source) ?
10.Cookie操作
# 1.獲取所有的cookie: for cookie in driver.get_cookies(): ? ? print(cookie) # 2.根據(jù)cookie的key獲取value: value = driver.get_cookie(key) # 3.刪除所有的cookie: driver.delete_all_cookies() # 4.刪除某個(gè)cookie: driver.delete_cookie(key) # 添加cookie: driver.add_cookie({"name":"password","value":"111111"}) ?
11.模擬登錄
這里模擬登錄我們學(xué)校教務(wù)處:
from selenium.webdriver import Chrome if __name__ == '__main__': ? ? web = Chrome() ? ? web.get('http://bkjx.wust.edu.cn/') ? ? username = web.find_element_by_id('userAccount') ? ? username.send_keys('xxxxxxx') # 這里填自己的學(xué)號(hào) ? ? password = web.find_element_by_id('userPassword') ? ? password.send_keys('xxxxxxx') # 這里填自己的密碼 ? ? btn = web.find_element_by_xpath('//*[@id="ul1"]/li[4]/button') ? ? btn.click() ? ? # do something ?
因?yàn)闆]有滑塊啥的驗(yàn)證,所以就很簡單qwq。然后后面進(jìn)行自己的操作即可。
12.優(yōu)缺點(diǎn)
selenium能夠執(zhí)行頁面上的js,對(duì)于js渲染的數(shù)據(jù)和模擬登陸處理起來非常容易。
selenium由于在獲取頁面的過程中會(huì)發(fā)送很多請(qǐng)求,所以效率非常低,所以在很多時(shí)候需要酌情使用。
到此這篇關(guān)于Python-Selenium自動(dòng)化爬蟲的文章就介紹到這了,更多相關(guān) Selenium自動(dòng)化爬蟲內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Django的CSRF認(rèn)證實(shí)現(xiàn)
這篇文章主要介紹了詳解Django的CSRF認(rèn)證實(shí)現(xiàn),詳細(xì)的介紹了csrf原理和實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10Python 字符串大小寫轉(zhuǎn)換的簡單實(shí)例
下面小編就為大家?guī)硪黄狿ython 字符串大小寫轉(zhuǎn)換的簡單實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01Python實(shí)現(xiàn)讀取文件夾按數(shù)字排序功能
這篇文章主要介紹了Python讀取文件夾按數(shù)字排序,代碼簡單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-09Python使用combinations實(shí)現(xiàn)排列組合的方法
今天小編就為大家分享一篇Python使用combinations實(shí)現(xiàn)排列組合的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-11-11tensorflow轉(zhuǎn)onnx的實(shí)現(xiàn)方法
本文主要介紹了tensorflow轉(zhuǎn)onnx的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03