七、Selenium與phantomJS----------動態頁面模擬點擊、網站模擬登錄


每天一個小實例1(動態頁面模擬點擊,並爬取你想搜索的職位信息)

 1 from selenium import webdriver
 2 from bs4 import BeautifulSoup
 3 
 4 # 調用環境變量指定的PhantomJS瀏覽器創建瀏覽器對象
 5 driver = webdriver.PhantomJS()
 6 
 7 #訪問的網址,我這里是登錄的boss直聘
 8 driver.get('https://www.zhipin.com/')
 9 
10 #模擬在搜索框輸入你想搜索的內容
11 search_content = input('請輸入你要搜索的內容:')
12 driver.find_element_by_xpath('//input[@name="query"]').send_keys(search_content)
13 
14 #模擬點擊搜索按鈕
15 driver.find_element_by_class_name('btn-search').click()
16 
17 #我要爬取前10頁的招聘信息
18 page_num = 1
19 
20 while page_num <11:
21      #創建BeautifulSoup對象, 指定解析器。為了提取出登錄所用的數據
22      soup = BeautifulSoup(driver.page_source, 'lxml')
23 
24     #我提取的是職位名稱,工資,公司
25      position_list =soup.find_all(name='div',class_='job-title')
26 
27      salary_list=soup.select('.info-primary h3 a span')
28 
29      company_list =soup.select('.company-text a')
30 
31 #將提取的信息保存到work.txt中
32      for position,salary,company in zip(position_list,salary_list,company_list):
33           with open('work.txt','a') as f:
34                f.write(position.get_text().strip() + ' |')
35                f.write(salary.get_text().strip() + ' |')
36                f.write(company.get_text().strip())
37                f.write('\n')
38 
39 #模擬點擊下一頁
40      driver.find_element_by_class_name('next').click()
41      page_num +=1
42 
43 #退出
44 driver.quit()

 

結果:

請輸入你要搜索的內容:python爬蟲

 

 


 每天一個小實例2(模擬網站登錄)

 1 # boss.py
 2 
 3 from selenium import webdriver
 4 import time
 5 
 6 driver = webdriver.PhantomJS()
 7 driver.get("https://login.zhipin.com/")
 8 
 9 # 生成訪問的后快照
10 driver.save_screenshot("boss1.png")
11 #可以打開boss.png查看驗證碼,然后手動登錄:
12 captcha = input('請輸入驗證碼:')
13 
14 # 輸入賬號密碼
15 driver.find_element_by_name("account").send_keys(賬號)
16 driver.find_element_by_name("password").send_keys(密碼)
17 driver.find_element_by_name("captcha").send_keys(驗證碼)
18 # 模擬點擊登錄
19 driver.find_element_by_xpath("//button[@class='btn']").click()
20 
21 # 等待2秒
22 time.sleep(2)
23 
24 # 生成登陸后快照
25 driver.save_screenshot("boss2.png")
26 
27 
28 #退出
29 driver.quit()

 

結果:

請輸入驗證碼:fcwg

 

登錄前后截圖:


 基本應用:

我用的是Python3、selenium2.53.5、PhantomJS

Selenium(最新版本的Selenium已經不支持PhantomJS了,要想用請下載較低的版本)

  selenium是一個Web的自動化測試工具,最初是為網站自動化測試而開發的,類型像我們玩游戲用的按鍵精靈,可以按指定的命令自動操作,不同是Selenium 可以直接運行在瀏覽器上,它支持所有主流的瀏覽器(包括PhantomJS這些無界面的瀏覽器)。

  Selenium 可以根據我們的指令,讓瀏覽器自動加載頁面,獲取需要的數據,甚至頁面截屏,或者判斷網站上某些動作是否發生。

  Selenium 自己不帶瀏覽器,不支持瀏覽器的功能,它需要與第三方瀏覽器結合在一起才能使用。但是我們有時候需要讓它內嵌在代碼中運行,所以我們可以用一個叫 PhantomJS 的工具代替真實的瀏覽器。

  可以從 PyPI 網站下載 Selenium庫https://pypi.python.org/simple/selenium ,也可以用 第三方管理器 pip用命令安裝:pip install selenium

  Selenium 官方參考文檔:http://selenium-python.readthedocs.io/index.html

 

PhantomJS

  PhantomJS 是一個基於Webkit的“無界面”(headless)瀏覽器,它會把網站加載到內存並執行頁面上的 JavaScript,因為不會展示圖形界面,所以運行起來比完整的瀏覽器要高效。

  如果我們把 Selenium 和 PhantomJS 結合在一起,就可以運行一個非常強大的網絡爬蟲了,這個爬蟲可以處理 JavaScrip、Cookie、headers,以及任何我們真實用戶需要做的事情。

  注意:PhantomJS 只能從它的官方網站http://phantomjs.org/download.html) 下載。 因為 PhantomJS 是一個功能完善(雖然無界面)的瀏覽器而非一個 Python 庫,所以它不需要像 Python 的其他庫一樣安裝,但我們可以通過Selenium調用PhantomJS來直接使用。

  PhantomJS 官方參考文檔:http://phantomjs.org/documentation


  Selenium 庫里有個叫 WebDriver 的 API。WebDriver 有點兒像可以加載網站的瀏覽器,但是它也可以像 BeautifulSoup 或者其他 Selector 對象一樣用來查找頁面元素,與頁面上的元素進行交互 (發送文本、點擊等),以及執行其他動作來運行網絡爬蟲。

 1 #導入webdriver
 2 from selenium import webdriver
 3 
 4 # 調用環境變量指定的PhantomJS瀏覽器創建瀏覽器對象
 5 driver = webdriver.PhantomJS()
 6 
 7 # 如果沒有在環境變量指定PhantomJS位置
 8 # driver = webdriver.PhantomJS(executable_path="./phantomjs"))
 9 
10 # get方法會一直等到頁面被完全加載,然后才會繼續程序.
11 driver.get('https://baidu.com/')
12 
13 #打印頁面標題
14 title = driver.title
15 print(title)
16 
17 #支持很多提取數據的方法。我這里用的xpath,取a[@class="mnav"]中的文本
18 data_titles = driver.find_elements_by_xpath('//a[@class="mnav"]')
19 for title in data_titles:
20     print(title.text)
21 
22 # 生成當前頁面快照並保存
23 driver.save_screenshot("baidu.png")
24 
25 # 獲取當前頁面Cookie
26 print(driver.get_cookies())
27 
28 # 獲取當前url
29 print(driver.current_url)
30 
31 # 關閉瀏覽器
32 driver.quit()
View Code

結果:

1 百度一下,你就知道
2 新聞
3 hao123
4 地圖
5 視頻
6 貼吧
7 學術
8 [{'domain': 'www.baidu.com', 'expires': '周二, 06 三月 2018 07:10:23 GMT', 'expiry': 1520320223, 'httponly': False, 'name': 'BD_UPN', 'path': '/', 'secure': False, 'value': '14314354'}, {'domain': '.baidu.com', 'expires': '周三, 16 二月 2050 07:10:22 GMT', 'expiry': 2528608222, 'httponly': False, 'name': 'BIDUPSID', 'path': '/', 'secure': False, 'value': '21EAAAD67FC8DC7AE83C40A04DD9C97C'}, {'domain': '.baidu.com', 'httponly': False, 'name': 'H_PS_PSSID', 'path': '/', 'secure': False, 'value': '25638_1431_21089_17001'}, {'domain': 'www.baidu.com', 'httponly': False, 'name': 'BD_HOME', 'path': '/', 'secure': False, 'value': '0'}, {'domain': '.baidu.com', 'expires': '周四, 14 三月 2086 10:24:29 GMT', 'expiry': 3666939869, 'httponly': False, 'name': 'PSTM', 'path': '/', 'secure': False, 'value': '1519456198'}, {'domain': '.baidu.com', 'expires': '周四, 14 三月 2086 10:24:29 GMT', 'expiry': 3666939869, 'httponly': False, 'name': 'BAIDUID', 'path': '/', 'secure': False, 'value': 'E38EDFD24E6C7A1EFE02929130C63429:FG=1'}]
9 https://www.baidu.com/
View Code

獲取的截圖:

  從頁面中提取元素:

 1 from selenium import webdriver
 2 
 3 driver = webdriver.PhantomJS()
 4 #---------------------------------------------------------------
 5 #假設下面有一個表單輸入框:
 6 # <input type="text" name="user-name" id="passwd-id" />
 7 
 8 # 獲取id標簽值
 9 element = driver.find_element_by_id("passwd-id")
10 #或者:
11 '''from selenium.webdriver.common.by import By
12 element = driver.find_element(by=By.ID, value="coolestWidgetEvah")
13 以下的類推
14 '''
15 
16 # 獲取name標簽值
17 element = driver.find_element_by_name("user-name")
18 # 獲取標簽名值
19 element = driver.find_elements_by_tag_name("input")
20 # 也可以通過XPath來匹配
21 element = driver.find_element_by_xpath("//input[@id='passwd-id']")
22 
23 
24 #--------------------------------------------------------------
25 #<a href="http://www.google.com/search?q=cheese">cheese</a>
26 cheese = driver.find_element_by_link_text("cheese")
27 
28 #--------------------------------------------------------------
29 #<a href="http://www.google.com/search?q=cheese">search for cheese</a>>
30 cheese = driver.find_element_by_partial_link_text("cheese")
31 #by css
32 cheese = driver.find_element_by_css_selector("a")
View Code

 

  有些時候,我們需要再頁面上模擬一些鼠標操作,比如雙擊、右擊、拖拽甚至按住不動等,我們可以通過導入 ActionChains 類來做到:

 1 #導入 ActionChains 類
 2 from selenium.webdriver import ActionChains
 3 
 4 # 鼠標移動到 登錄按鈕 位置,
 5 login = driver.find_element_by_xpath('//input[@text='button']')
 6 ActionChains(driver).move_to_element(login).perform()
 7 
 8 
 9 # 在 login 位置單擊
10 
11 ActionChains(driver).move_to_element(login).click(login).perform()
12 
13 # 在 login 位置雙擊
14 
15 ActionChains(driver).move_to_element(login).double_click(login).perform()
16 
17 # 在 login位置右擊
18 
19 ActionChains(driver).move_to_element(ac).context_click(ac).perform()
20 
21 # 在 login位置左鍵單擊hold住
22 a
23 ActionChains(driver).move_to_element(login).click_and_hold(login).perform()
24 
25 # 將 ac1 拖拽到 ac2 位置
26 ac1 = driver.find_element_by_xpath('elementD')
27 ac2 = driver.find_element_by_xpath('elementE')
28 ActionChains(driver).drag_and_drop(ac1, ac2).perform()
View Code

  有時候我們會碰到<select> </select>標簽的下拉框。直接點擊下拉框中的選項不一定可行。Selenium專門提供了Select類來處理下拉框。 其實 WebDriver 中提供了一個叫 Select 的方法,可以幫助我們完成這些事情:

1 <select id="status" class="form-control valid" onchange="" name="status">
2     <option value=""></option>
3     <option value="0">未審核</option>
4     <option value="1">初審通過</option>
5     <option value="2">復審通過</option>
6     <option value="3">審核不通過</option>
7 </select>
 1 # 導入 Select 類
 2 from selenium.webdriver.support.ui import Select
 3 
 4 # 找到 name 的選項卡
 5 select = Select(driver.find_element_by_name('status'))
 6 
 7 # 
 8 select.select_by_index(1)
 9 select.select_by_value("0")
10 select.select_by_visible_text("未審核")
11 
12 
13 #index 索引從 0 開始
14 #value是option標簽的一個屬性值,並不是顯示在下拉框中的值
15 #visible_text是在option標簽文本的值,是顯示在下拉框的值
View Code

  當你觸發了某個事件之后,頁面出現了彈窗提示,處理這個提示或者獲取提示信息方法如下:

alert = driver.switch_to_alert()

 

  一個瀏覽器肯定會有很多窗口,所以我們肯定要有方法來實現窗口的切換。切換窗口的方法如下:

driver.switch_to.window("窗口名")

#也可以使用 window_handles 方法來獲取每個窗口的操作對象。例如:

for handle in driver.window_handles:
    driver.switch_to_window(handle)

 

  操作頁面的前進和后退功能:

driver.forward()     #前進

driver.back()        # 后退

 

  Cookies:

#獲取頁面每個Cookies值,用法如下:
for cookie in driver.get_cookies():
    print "%s -> %s" % (cookie['name'], cookie['value'])

#刪除Cookies,用法如下:
# By name
driver.delete_cookie("CookieName")

# all
driver.delete_all_cookies()

  現在的網頁越來越多采用了 Ajax 技術,這樣程序便不能確定何時某個元素完全加載出來了。如果實際頁面等待時間過長導致某個元素還沒出來,但是你的代碼直接使用了這個元素,那么就會拋出NullPointer的異常。

  所以 Selenium 提供了兩種等待方式,一種是隱式等待,一種是顯式等待。

    隱式等待是等待特定的時間,顯式等待是指定某一條件直到這個條件成立時繼續執行。

  顯式等待:

  顯式等待指定某個條件,然后設置最長等待時間。如果在這個時間還沒有找到元素,那么便會拋出異常了。

 1 from selenium import webdriver
 2 from selenium.webdriver.common.by import By
 3 # WebDriverWait 庫,負責循環等待
 4 from selenium.webdriver.support.ui import WebDriverWait
 5 # expected_conditions 類,負責條件出發
 6 from selenium.webdriver.support import expected_conditions as EC
 7 
 8 driver = webdriver.PhantomJS()
 9 driver.get("http://www.xxxxx.com/loading")
10 try:
11     # 頁面一直循環,直到 id="myDynamicElement" 出現即返回。
12 #如果不寫參數,程序默認會 0.5s 調用一次來查看元素是否已經生成,如果本來元素就是存在的,那么會立即返回。
13     element = WebDriverWait(driver, 10).until(
14         EC.presence_of_element_located((By.ID, "myDynamicElement"))
15     )
16 finally:
17     driver.quit()

 

 下面是一些內置的等待條件,你可以直接調用這些條件,而不用自己寫某些等待條件了:

 1 title_is
 2 title_contains
 3 presence_of_element_located
 4 visibility_of_element_located
 5 visibility_of
 6 presence_of_all_elements_located
 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 element_to_be_clickable – it is Displayed and Enabled.
12 staleness_of
13 element_to_be_selected
14 element_located_to_be_selected
15 element_selection_state_to_be
16 element_located_selection_state_to_be
17 alert_is_present

 隱式等待

隱式等待比較簡單,就是簡單地設置一個等待時間,單位為秒。

1 from selenium import webdriver
2 
3 driver = webdriver.PhantomJS()
4 driver.implicitly_wait(10) # seconds
5 driver.get("http://www.xxxxx.com/loading")
6 myDynamicElement = driver.find_element_by_id("myDynamicElement")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM