selenium模塊介紹
selenium最初是一個測試工具,而爬蟲中使用它主要是為了解決requests無法直接執行JavaScript代碼的問題
selenium本質是通過驅動瀏覽器,完全模擬瀏覽器的操作,比如跳轉、輸入、點擊、下拉等,來拿到網頁渲染之后的結果,能支持多種瀏覽器。
Selenium自己不帶瀏覽器,不支持瀏覽器的功能,它需要與第三方瀏覽器結合在一起才能使用。但是我們有時候需要讓它內嵌在代碼中運行,所有我們而已用一個叫PhantomJS的工具代替真實的瀏覽器。
Selenium官方參考文檔:`http://selenium-python.readthedocs.io/index.html`
from selenium import webdriver browser=webdriver.Chrome() browser=webdriver.Firefox() browser=webdriver.PhantomJS() #無窗口瀏覽器 browser=webdriver.Safari()
安裝
安裝:selenium+chromedriver
pip3 install selenium
chromedriver:
下載地址:http://chromedriver.storage.googleapis.com/index.html
chromedriver與chrome的對應關系表
chromedriver版本 | 支持的Chrome版本 |
---|---|
v2.37 | v64-66 |
v2.36 | v63-65 |
v2.35 | v62-64 |
v2.34 | v61-63 |
v2.33 | v60-62 |
v2.32 | v59-61 |
v2.31 | v58-60 |
v2.30 | v58-60 |
v2.29 | v56-58 |
v2.28 | v55-57 |
v2.27 | v54-56 |
v2.26 | v53-55 |
v2.25 | v53-55 |
v2.24 | v52-54 |
v2.23 | v51-53 |
v2.22 | v49-52 |
v2.21 | v46-50 |
v2.20 | v43-48 |
v2.19 | v43-47 |
v2.18 | v43-46 |
v2.17 | v42-43 |
v2.13 | v42-45 |
v2.15 | v40-43 |
下載之后放到放到python安裝路徑的目錄中即可
代碼測試
from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--window-position=0,0'); # chrome 啟動初始位置 options.add_argument('--window-size=1080,800'); # chrome 啟動初始大小 # options.add_argument('--proxy-server=http://ip:port') # options.add_arguments("start-maximized") 最大化窗口 browser=webdriver.Chrome(chrome_options=options) browser.get('http://www.baidu.com') print(browser.page_source)
安裝:selenium+phantomjs
下載phantomjs,解壓后把phantomjs.exe所在的bin目錄放到環境變量
下載鏈接:http://phantomjs.org/download.html
需要把phantomjs.exe拷貝到你的python安裝路徑
代碼測試
from selenium import webdriver # browser=webdriver.Chrome() # browser=webdriver.Firefox() browser=webdriver.PhantomJS() # 無窗口瀏覽器 # 需要把phantomjs拷貝到你的python安裝路徑 browser.get('http://www.baidu.com') print(browser.page_source)
使用Headless Chrome
Headless模式是Chrome 59中的新特征,要使用Chrome需要安裝chromedriver
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') browser = webdriver.Chrome(chrome_options=chrome_options) browser.get("https://www.baidu.com/") print(browser.page_source) # 得到文本信息
頁面操作
Selenium的WebDriver提供了各種方法來尋找元素
對於一個表單框 <input type="text" name="user-name" id="user-id" /> #獲取id標簽值 element = browser.find_element_by_id("user-id") #獲取name值 element = browser.find_element_by_name("user-name") #獲取標簽名 element = browser.find_element_by_tag("input") #也可以通過XPath來匹配 element = browser.find_element_by_xpath('//*input[@id="user-id"]/')
元素選取
在一個頁面中有很多不同的策略可以定位一個元素。我們可以選擇最合適的方法去查找元素。Selenium提供了下列的方法:
單個元素: find_element_by_id find_element_by_name find_element_by_xpath find_element_by_link_text find_element_by_class_name find_element_by_css_selector 多個元素: find_elements_by_id ....
1. By ID
元素 <div id="id1">...</div>
# 實現 element = browser.find_element_by_id("id1") #---------or------- from selenium.webdriver.common.by import By element = browser.find_element(by=By.ID, value="id1")
2. By Class Name
<div class="cheese"><span>hihi</span></div> 實現 cheese = browser.find_element_by_class_name('cheese') # ----------------or-------------------- from selenium.webdriver.common.by import By cheese = browser.find_elements(By.CLASS_NAME, "cheese")
3.By Name
<input name="cheese" type="text" /> # 實現 cheese = browser.find_element_by_name("cheese") # -------------or------------------------- from selenium.webdrier.common.by import By cheese = browser.find_element(By.NAME, "cheese")
4. By Link Text
<a href="http://www.google.com/search?q=cheese">cheese</a> # 實現 cheese = browser.find_element_by_link_text("cheese") # ---------------------or----------------------- from selenium.webdriver.common.by import By cheese = browser.find_element(By.LINK_TEXT, "cheese")
5.By CSS
<div id="food"><span class="dairy">milk</span></div> 實現 cheese = browser.find_element_by_css_selector("#food span.dairy") # ----------------or------------------------------- from selenium.webdriver.common.by import By cheese = browser.find_element(By.CSS_SELECTOR, "#food span.dairy")
6.By XPath
<input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off"> 實現 inputs = browser.find_elements_by_xpath('//*[@id="kw"]') # -------------------or------------------ from selenium.webdriver.common.by import By inputs = browser.find_elements(By.XPATH, '//*[@id="kw"]')
7.By Partial Link Text
partial link text就是選擇這個元素的link text中一部分字段。
<a href="http://www.google.com/search?q=cheese">search for cheese</a> # 實現 cheese = driver.find_element_by_partial_link_text("cheese") # -----------------or----------------- from selenium.webdriver.common.by import By cheese = driver.find_element(By.PARTIAL_LINK_TEXT, "cheese")
8.使用案例
導入webdriver from selenium import webdriver import time #要想調用鍵盤按鍵操作需要引入keys包 from selenium.webdriver.common.keys import Keys #調用環境變量指定的PhantomJS瀏覽器創建瀏覽器對象 driver = webdriver.PhantomJS() driver.set_window_size(1920, 1080) # 此句必須加上,否則會報錯 #如果沒有在環境變量指定PhantomJS位置 #driver = webdriver.PhantomJS(executable_path = "C:\phantomjs\bin\phantomjs.exe") #get方法會一直等到頁面加載,然后才會繼續程序,通常測試會在這里選擇time.sleep(2) time.sleep(2) driver.get("http://www.baidu.com/") # 獲取css=#u1 > a:nth-child(1)文本內容 data = driver.find_element_by_css_selector('#u1 > a:nth-child(1)').text # 打印數據內容 print(data) # 新聞 # 生成頁面快照並保存 driver.save_screenshot("baidu.png") # 搜索 # # id="kw"是百度搜索輸入框,輸入字符串"長城" driver.find_element_by_id('kw').send_keys('長城') # id="su"是百度搜索按鈕,click()是模擬點擊 driver.find_element_by_id('su').click() time.sleep(1) # 獲取新的頁面快照 driver.save_screenshot("長城.png") # 打印網頁渲染后的源代碼 print(driver.page_source) # 獲取當前頁面Cookie print('cookies: ',driver.get_cookies()) # #ctrl+a全選輸入框內容 driver.find_element_by_id('kw').send_keys(Keys.CONTROL, 'a') #ctrl+x剪切輸入框內容 driver.find_element_by_id('kw').send_keys(Keys.CONTROL, 'x') # #輸入框重新輸入內容 driver.find_element_by_id('kw').send_keys('python') # # 模擬Enter回車鍵 driver.find_element_by_id('su').send_keys(Keys.RETURN) time.sleep(5) # 清空輸入框內容 driver.find_element_by_id('kw').clear() #生成新的頁面快照 driver.save_screenshot('python.png') #獲取當前url print(driver.current_url) driver.quit()
driver.close()
頁面交互
彈窗處理
當你觸發了某個事件之后,頁面出現了彈窗提示,處理這個提示或者獲取提示信息方法如下
alert = driver.switch_to_alert()
alert.accept()
窗口切換
首先通過driver.window_handles獲取每個窗口的操作對象, 然后for循環達到切換窗口的目的。
for handle in driver.window_handles:
driver.switch_to_window(handle)
#選項卡管理:切換選項卡,有js的方式windows.open,有windows快捷鍵:ctrl+t等,最通用的就是js的方式 import time from selenium import webdriver browser=webdriver.Chrome() browser.get('https://www.baidu.com') browser.execute_script('window.open()') print(browser.window_handles) #獲取所有的選項卡 browser.switch_to_window(browser.window_handles[1]) browser.get('https://www.taobao.com') time.sleep(10) browser.switch_to_window(browser.window_handles[0]) browser.get('https://www.sina.com.cn') browser.close()
JS執行
from selenium import webdriver try: browser=webdriver.Chrome() browser.get('https://www.baidu.com') browser.execute_script('alert("hello world")') #打印警告 time.sleep(10) finally: browser.close()
頁面的前進和后退
操作頁面的前進和后退功能:
import time from selenium import webdriver browser=webdriver.Chrome() browser.get('https://www.baidu.com') browser.get('https://www.taobao.com') browser.get('http://www.sina.com.cn/') browser.back() time.sleep(10) browser.forward() browser.close()
Cookies
獲取頁面每個Cookies值,用法如下:
from selenium import webdriver browser = webdriver.Chrome() browser.get('https://www.baidu.com/') # print(browser.get_cookies()) for cookie in browser.get_cookies(): print("%s -> %s"%(cookie['name'], cookie['value']))
刪除Cookies,用法如下:
#By name
driver.delete_cookie('CookieName')
#all
driver.delete_all_cookies()
frame切換
try: browser=webdriver.Chrome() browser.get('http://www.runoob.com/try/try.php?filename=tryjs_while') browser.switch_to.frame('iframeResult') #切換到id為iframeResult的frame time.sleep(3) tag1=browser.find_element_by_id('demo') print(tag1) # tag2=browser.find_element_by_id('textareaCode') #報錯,在子frame里無法查看到父frame的元素 browser.switch_to.parent_frame() #切回父frame,就可以查找到了 time.sleep(3) tag2=browser.find_element_by_id('textareaCode') print(tag2) finally: browser.close()
元素的拖動
ActionChains的執行原理就是當調用ActionChains方法的時候不會立即執行,而是將所有的操作暫時存儲在一個隊列中,當調用perform()的方法時候,隊列會按照放入的先后順序依次執行。
ActionChains提供的方法 click(on_element=None) #單擊鼠標左鍵 click_and_hold(on_element=None) #點擊鼠標左鍵,按住不放 context_click(on_element=None) #點擊鼠標右鍵 double_click(on_element=None) #雙擊鼠標左鍵 drag_and_drop(source,target) #拖拽到某個元素然后松開 drag_and_drop_by_offset(source,xoffset, yoffset)#拖拽到某個坐標然后松開 move_by_offset(xoffset,yoffset) #鼠標移動到距離當前位置(x,y) move_to_element(to_element) #鼠標移動到某個元素 move_to_element_with_offset(to_element,xoffset, yoffset) #將鼠標移動到距某個元素多少距離的位置 release(on_element=None) #在某個元素位置松開鼠標左鍵 perform() #執行鏈中的所有動作
示例:
#導入ActionChains類 from selenium.webdriver.common.action_chains import ActionChains #鼠標移動到ac位置 ac = driver.find_elenemt_by_xpath('element') ActionChains(driver).move_to_element(ac).perform() #在ac位置單擊 ac = driver.find_element_by_xpath('elementA') ActionChains(driver).move_to_element(ac).click(ac).perform() #在ac位置雙擊 ac = driver.find_element_by_xpath("elementB") ActionChains(driver).move_to_element(ac).double_click(ac).perform() #在ac位置右擊 ac = driver.find_element_by_xpath('elementC') ActionChains(driver).move_to_element(ac).context_click(ac).perform() #在ac位置左鍵單擊hold住 ac = driver.find_element_by_xpath('elementF') ActionChains(driver).move_to_element(ac).click_and_hold(ac).perform() #將ac1拖拽到ac2位置 ac1 = driver.find_element_by_xpath('elementD') ac2 = driver.find_element_by_xpath('elementE') ActionChains(driver).drag_and_drop(ac1, ac2).perform()
實例
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time driver = webdriver.Chrome() try: driver.get('http://www.treejs.cn/v3/demo/cn/exedit/drag.html') time.sleep(5) element = driver.find_element_by_id('treeDemo_1_span') target = driver.find_element_by_id('treeDemo_17_span') ActionChains(driver).drag_and_drop(element, target).perform() time.sleep(10) finally: driver.quit()
填充表單
我們已經知道了怎樣向文本框輸入文字,但是有時候我們會碰到<select></select>
標簽的下拉框。直接點擊下拉框中的選項不一定可行。
<select id="status" class="form-control valid" onchange="" name = 'status'> <option value=""></option> <option value="0">未審核</option> <option value="1">初審通過</option> <option value="2">復審通過</option> <option value="3">審核不通過</option> </select>
Selenium專門提供了Select類來處理下拉框。其實WebDriver中提供了一個叫Select的方法,可以幫助我們完成這些事情:
# 導入Select類 from selenium.webdriver.support.ui import Select driver = webdriver.PhantomJS() #找到name的選項卡 select = Select(driver.find_element_by_name('status')) #s select.select_by_index(1) select.select_by_value("0") select.select_by_visible_text('未審核') # 以上是三種選擇下拉框的方式,它可以根據索引來選擇,可以根據值來選擇,可以根據文字來選擇。注意: # # index索引從0開始 # value是option標簽的一個屬性值,並不是顯示在下拉框中的值 # visible_text實在option標簽文本的值,是顯示在下拉框的值 # 全部取消選擇怎么辦呢?很簡單: select.deselect_all()
頁面等待
在selenium當中共有兩種等待頁面加載的方式,顯示等待和隱示等待。
顯式等待
顯式等待指定某個條件,然后設置最長等待時間。如果在這個時間還沒有找到元素,那么便會拋出異常了。
顯示等待主要使用了WebDriverWait類與expected_conditions模塊。
WebDriverWait類是顯性等待類,先看下它有哪些參數與方法:
init
driver: 傳入WebDriver實例。 timeout: 超時時間,等待的最長時間(同時要考慮隱性等待時間) poll_frequency: 調用until中的方法的間隔時間,默認是0.5秒 ignored_exceptions:忽略的異常,如果在調用until的過程中拋出這個元組中的異常, 則不中斷代碼,繼續等待,如果拋出的是這個元組外的異常,則中斷代碼,拋出異常。默認只有NoSuchElementException。
until
method: 在等待期間,每隔一段時間調用這個傳入的方法,直到返回值不是False message:如果超時,拋出TimeoutException,將message傳入異常
expected_conditions是selenium的一個模塊,其中包含一系列可用於判斷的條件: 這兩個條件類驗證title,驗證傳入的參數title是否等於或包含於driver.title title_is title_contains 這兩個人條件驗證元素是否出現,傳入的參數都是元組類型的locator,如(By.ID,'kw') 顧名思義,一個只要一個符合條件的元素加載出來就通過;另一個必須所有符合條件的元素都加載出來才行 presence_of_element_located presence_of_all_elements_located 這三個條件驗證元素是否可見,前兩個傳入參數是元組類型的locator,第三個傳入WebElement 第一個和第三個其實質是一樣的 visibility_of_element_located invisibility_of_element_located visibility_of 這兩個人條件判斷某段文本是否出現在某元素中,一個判斷元素的text,一個判斷元素的value text_to_be_present_in_element text_to_be_present_in_element_value 這個條件判斷frame是否可切入,可傳入locator元組或者直接傳入定位方式:id、name、index或WebElement frame_to_be_available_and_switch_to_it 這個條件判斷是否有alert出現 alert_is_present 這個條件判斷元素是否可點擊,傳入locator element_to_be_clickable
代碼使用
from selenium import webdriver from selenium.webdriver.common.by import By #WebDriverWait庫,負責循環等待 from selenium.webdriver.support.ui import WebDriverWait #expected_conditions類,負責條件觸發 from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("http://www.xxxx.com/") try: #頁面一直循環,直到id="myDynamicElement"出現 element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "loginname")) ) finally: driver.quit()
代碼舉例
from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get('https://baidu.com') locator = (By.LINK_TEXT, '貼吧') try: WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator)) print(driver.find_element_by_link_text('貼吧').get_attribute('href')) finally: driver.close()
弊端就是程序會一直等待整個頁面加載完成,就算你需要的元素加載出來了還是需要等待
from selenium import webdriver driver = webdriver.Chrome() driver.implicitly_wait(30) driver.get('https://www.baidu.com')
異常處理
from selenium import webdriver from selenium.common.exceptions import TimeoutException, NoSuchElementException,NoSuchFrameException try: browser = webdriver.Chrome() browser.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable') browser.switch_to.frame('iframssseResult') except TimeoutException as e: print(e) except NoSuchFrameException as e: print(e) finally: browser.close()
phantomjs介紹
phantomjs常用配置
# 引入配置對象DesiredCapabilities fromselenium.webdriver.common.desired_capabilities import DesiredCapabilities dcap =dict(DesiredCapabilities.PHANTOMJS) #從USER_AGENTS列表中隨機選一個瀏覽器頭,偽裝瀏覽器 dcap["phantomjs.page.settings.userAgent"]= (random.choice(USER_AGENTS)) # 不載入圖片,爬頁面速度會快很多 dcap["phantomjs.page.settings.loadImages"]= False # 設置代理 service_args =['--proxy=127.0.0.1:9999','--proxy-type=socks5'] #打開帶配置信息的phantomJS瀏覽器 driver =webdriver.PhantomJS(phantomjs_driver_path,desired_capabilities=dcap,service_args=service_args)
模擬登錄微博
from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 提供事件 from selenium.webdriver.common.by import By import time #如果獲取頁面時獲取不到文本內容,加入下面參數 browser = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=any']) browser.set_window_size(1366, 768) browser.get('https://weibo.com/') # print(driver.page_source) #輸入賬號和密碼 try: username = '908099665' pwd = '123456' wait = WebDriverWait(browser, 20, 0.5) wait.until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="loginname"]'))) wait.until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="pl_login_form"]/div/div[3]/div[2]/div/input'))) user = browser.find_element_by_xpath('//*[@id="loginname"]') user.clear() # 清除數據 user.send_keys(username) # 輸入數據 time.sleep(5) password = browser.find_element_by_xpath('//*[@id="pl_login_form"]/div/div[3]/div[2]/div/input') password.send_keys(pwd) # 輸入數據 page = browser.find_element_by_xpath('//*[@id="pl_login_form"]/div/div[3]/div[6]/a').click() # 點擊按鈕跳轉 # print(browser.page_source) # 得到文本信息 time.sleep(5) # 生成登錄后快照 with open('weibo.html', 'w',encoding='utf-8') as f: f.write(browser.page_source) # 寫入文本信息 except Exception as e: print(e) finally: browser.quit() #退出驅動
爬取京東商城商品信息
import time from selenium import webdriver from selenium.webdriver.common.keys import Keys # 鍵盤按鍵操作 def get_goods(driver): try: goods = driver.find_elements_by_class_name('gl-item') for good in goods: detail_url = good.find_element_by_tag_name('a').get_attribute('href') # J_goodsList > ul > li:nth-child(5) > div > div.p-price > strong > i # J_goodsList > ul > li:nth-child(1) > div > div.p-name.p-name-type-2 > a > em > font p_name = good.find_element_by_css_selector('.p-name em').text.replace('\n', '') price = good.find_element_by_css_selector('.p-price i').text p_commit = good.find_element_by_css_selector('.p-commit a').text msg = ''' 商品 : %s 鏈接 : %s 價錢 :%s 評論 :%s ''' % (p_name, detail_url, price, p_commit) print(msg, end='\n\n') button = driver.find_element_by_partial_link_text('下一頁') # button = driver.find_element_by_xpath('//*[@id = "J_bottomPage"]/span[1]/a[9]/em') button.click() time.sleep(1) print('-----------下一頁------------') get_goods(driver) except Exception: pass def spider(url, keyword): driver = webdriver.Chrome() driver.get(url) driver.implicitly_wait(3) # 使用隱式等待 try: input_tag = driver.find_element_by_id('key') input_tag.send_keys(keyword) input_tag.send_keys(Keys.ENTER) get_goods(driver) finally: driver.close() if __name__ == '__main__': spider('https://www.jd.com/', keyword='iPhoneX手機')
自動登錄163並且自動發送郵箱
from selenium import webdriver browser=webdriver.Chrome() wait = browser.implicitly_wait(10) try: browser.get('http://mail.163.com/') #首先先切到ifame下面 frame = browser.switch_to.frame("x-URS-iframe") input_user = browser.find_element_by_name("email") input_pwd = browser.find_element_by_name("password") loginbutton = browser.find_element_by_id("dologin") input_user.send_keys("aaa") #輸入郵箱 input_pwd.send_keys("aaa") #輸入密碼 loginbutton.click() #點擊登錄 # 如果遇到驗證碼,可以把下面一小段打開注釋 # import time # time.sleep(10) # button = browser.find_element_by_id('dologin') # button.click() #登錄完成之后開始點擊寫信 write_msg = browser.find_element_by_xpath("//div[@id='dvNavTop']//li[2]") #獲取第二個li標簽就是“寫信”了 print(write_msg.text) write_msg.click() #點擊寫信按鈕 #找到寫信的輸入框輸入內容 recv_man = browser.find_element_by_class_name('nui-editableAddr-ipt') #收件人 title = browser.find_element_by_css_selector('.dG0 .nui-ipt-input') #標題 content = browser.find_element_by_class_name("nui-scroll") recv_man.send_keys("1234567@qq.com") title.send_keys("每天都要開心,開心最重要!!!") print(title.tag_name) #輸入要發送的內容 frame = browser.find_element_by_class_name("APP-editor-iframe") frame = browser.switch_to.frame(frame) body = browser.find_element_by_xpath("//body") print(body.text) body.send_keys("啦啦啦啦啦啦") #找到發送按鈕。點擊發送 browser.switch_to.parent_frame() # 切回他爹 send_button = browser.find_element_by_class_name('nui-toolbar-item') send_button.click() # 可以睡時間久一點別讓瀏覽器關掉,看看發送成功沒有 import time time.sleep(10000) finally: browser.quit()