爬蟲最終殺手鐧 --- PhantomJS 詳解(附案例)


一 . 認識Phantomjs

1.Phantomjs:無界面的瀏覽器

Selenium: 可以根據我們的指令,讓瀏覽器自動加載頁面,獲取需要的數據,甚至頁面截屏,或者判斷網站上某些動作是否發生。Selenium 自己不帶瀏覽器,不支持瀏覽器的功能,它需要與第三方瀏覽器結合在一起才能使用。但是我們有時候需要讓它內嵌在代碼中運行,所以我們可以用一個叫 Phantomjs 的工具代替真實的瀏覽器。

文檔地址:http://selenium-python.readthedocs.io/index.html

# 導入 webdriver
from selenium import webdriver
# 要想調用鍵盤按鍵操作需要引入keys包
from selenium.webdriver.common.keys 
import Keys
# 調用環境變量指定的Phantomjs瀏覽器創建瀏覽器對象
driver = webdriver.Phantomjs()
# 如果沒有在環境變量指定Phantomjs位置# driver = webdriver.Phantomjs(executable_path="./phantomjs"))
# get方法會一直等到頁面被完全加載,然后才會繼續程序,通常測試會在這里選擇 time.sleep(2)
driver.get("http://www.baidu.com/")
# 獲取頁面名為 wrapper的id標簽的文本內容
data = driver.find_element_by_id("wrapper").text
# 打印數據內容
print data
# 打印頁面標題 "百度一下,你就知道
"print driver.title
# 生成當前頁面快照並保存
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()
# 獲取新的頁面快照
driver.save_screenshot("長城.png")
# 打印網頁渲染后的源代碼
print driver.page_source
# 獲取當前頁面Cookie
print 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("atguigu")
# 模擬Enter回車鍵
driver.find_element_by_id("su").send_keys(Keys.RETURN)
# 清除輸入框內容
driver.find_element_by_id("kw").clear()
# 生成新的頁面快照
driver.save_screenshot("atguigu.png")
# 獲取當前url
print driver.current_url
# 關閉當前頁面,如果只有一個頁面,會關閉瀏覽器# driver.close()
# 關閉瀏覽器
driver.quit()

  

 

2.頁面操作大體內容

# 獲取id標簽值
element = driver.find_element_by_id("passwd-id")
# 獲取name標簽值
element = driver.find_element_by_name("user-name")
# 獲取標簽名值
element = driver.find_elements_by_tag_name("input")
# 也可以通過XPath來匹配
element = driver.find_element_by_xpath("//input[@id='passwd-id']")

  

 

3. 關於元素的選取,有如下的API 單個元素選取

# 定位UI元素 (WebElements)
 
find_element_by_id
find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector

  

虎課網https://www.wode007.com/sites/73267.html 設計塢https://www.wode007.com/sites/73738.html

4. 鼠標動作鏈

# 導入 webdriver
 
#導入 ActionChains 類
from selenium.webdriver import ActionChains
# 鼠標移動到 ac 位置
ac = driver.find_element_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()

  

 

5 . 下拉菜單的操作(導入select類)

# 導入 Select 類
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.get("http://127.0.0.1:8080")
# 找到 name 的選項卡
select = Select(driver.find_element_by_name('status'))
#根據位置下標
# select.select_by_index(1)
#根據值找到對應的選擇
# select.select_by_value("3")
#根據顯示值找到對應的選擇
select.select_by_visible_text("審核不通過")

  

 

6. 頁面切換

driver.switch_to.window("window name")

  

 

7. 操作頁面的前進和后退

driver.forward()     #前進
driver.back()        # 后退

  

 

8. 頁面等待

 

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

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

from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10) # seconds
driver.get("http://www.xxxxx.com/loading")

  

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

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.xxxxx.com/loading")
try:
    # 頁面一直循環,直到 id="myElement" 出現
    element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "myElement")))
finally:
    driver.quit()

  

 

二、網站模擬登錄豆瓣網

from selenium import webdriver
import time
 
# 創建一個瀏覽器客戶端,並且指定配置
# 如果是Phantomjs做瀏覽器客戶端還要設置路徑
# driver = webdriver.Phantomjs(executable_path="/usr/local/bin/phantomjs")
driver = webdriver.Chrome()
 
driver.get("https://www.douban.com/")
time.sleep(1)
driver.save_screenshot("豆瓣首頁.png")
 
#輸入賬號
driver.find_element_by_id("form_email").send_keys("username")
#輸入密碼
driver.find_element_by_name("form_password").send_keys("password")
#保存驗證碼的圖片
driver.save_screenshot("驗證碼.png")
#輸入驗證碼
check_code = input("請輸入驗證碼:")
print(r"驗證碼是多少:%s" % check_code)
 
driver.find_element_by_id("captcha_field").send_keys(check_code)
 
#點擊登錄按鈕
driver.find_element_by_xpath("//input[@class='bn-submit']").click()
 
#休眠一下等待登錄成功
time.sleep(3)
#保存登錄成功的快照
driver.save_screenshot("登錄成功.png")

  

#保存成功登錄好的html到本地 with open("douban.html","w",encoding="utf-8") as f: f.write(driver.page_source) #退出成功 driver.quit()

 

三、動態頁面模擬點擊(unittest -python測試模塊)

import time
#導入python測試模塊
import unittest
 
#類名任意,但必須繼承unittest.TestCase
class DouyuTest(unittest.TestCase):
   #固定寫法,通常做初始化
   def setUp(self):
      print("setUp()....")
      self.num1 = 1
      self.num2 = 1
 
   def testTest(self):
      for i in range(1,3):
         print("testTest()==",i)
         self.num1 += 1
         time.sleep(1)
 
   def testTest2(self):
      for i in range(1,3):
         print("testTest2()==",i)
         self.num2 += 1
         time.sleep(1)
   #固定寫法,但每個自定義方法接收后都會調用一次該方法
   def tearDown(self):
      print("tearDown()...")
      print("num1==",self.num1)
      print("num2==", self.num2)
 
if __name__ == "__main__":
   #調用的時候只需要寫上main,固定的調用方式
   unittest.main()

  

 

四、執行JavaScript代碼from selenium import webdriver

import time
 
driver = webdriver.PhantomJS()
 
driver.get("https://movie.douban.com/typerank?type_name=劇情&type=11&interval_id=100:90&action=")
# 向下滾動10000像素
js = "document.body.scrollTop=10000"
time.sleep(5)
#查看頁面快照
driver.save_screenshot("douban.png")
# 執行JS語句
driver.execute_script(js)
 
time.sleep(5)
#查看頁面快照
driver.save_screenshot("newdouban.png")
#退出瀏覽器
driver.quit()

  

 

五、模擬最新無界面瀏覽器(絕招在這,缺陷性能太慢)

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options
 
#不加載圖片,不緩存在硬盤(內存)
SERVICE_ARGS = ['--load-images=false', '--disk-cache=false']
chrome_options = Options()
chrome_options.add_argument("--headless")
# 創建瀏覽器, 添加參數設置為無界面瀏覽器
driver = webdriver.Chrome(service_args=SERVICE_ARGS, chrome_options=chrome_options)
#設置等待時間
waite = WebDriverWait(driver, 5)
driver.get('https://taobao.com/')
 
def get_page_num():
	# 等待搜索框出現
	input = waite.until(EC.presence_of_element_located((By.css_SELECTOR, '#q')))
	# 輸入美食
	input.send_keys('美食')
	# 點擊搜索
	driver.find_element_by_css_selector("#J_TSearchForm > div > button").click()
	# 共計多少頁
	text = driver.find_element_by_css_selector('#mainsrp-pager > div > div > div > div[class="total"]').text
	data = text[2:6]
	get_product_info()
	return data
 
#得到某一個寶貝,商品的大體信息
def get_product_info():
	waite.until(EC.presence_of_element_located((By.css_SELECTOR, '#mainsrp-itemlist .items .item')))
	# 通過BeautifulSoup取數據
	soup = BeautifulSoup(driver.page_source, 'lxml')
	#取所有的列表數據
	item_lists = soup.select("#mainsrp-itemlist .items .item")
	for item_list in item_lists:
		item_dict = {}
		image = item_list.select('.J_ItemPic.img')[0].attrs["data-src"]
		if not image:
			image = item_list.select('.J_ItemPic.img')[0].attrs["data-ks-lazyload"]
		# 銷售地
		location = item_list.select(".location")[0].text
		# 價格
		price = item_list.select(".price")[0].text
		# 商店名稱
		shopname = item_list.select(".shopname")[0].text.strip()
		# 寶貝名稱
		title = item_list.select('a[class="J_ClickStat"]')[0].text.strip()
		# 鏈接
		data_link = item_list.select('a[class="J_ClickStat"]')[0].attrs["href"]
 
		item_dict["image"] = "https:" + image
		item_dict["location"] = location
		item_dict["shopname"] = shopname
		item_dict["title"] = title
		item_dict["data_link"] = "https:" + data_link
		item_dict["price"] = price
		print(item_dict)
 
# 切換下一頁
def next_page(page):
	print("當前正在加載第%s頁的數據--------" % page)
	try:
		input = waite.until(EC.presence_of_element_located((By.css_SELECTOR, '#mainsrp-pager > div > div > div > div > input')))
		input.clear()   # 清空輸入框
		# 頁面框添加頁碼
		input.send_keys(page)
		#找到確定按鈕,點擊確定
		driver.find_element_by_css_selector("#mainsrp-pager > div > div > div > div > span.btn.J_Submit").click()
		waite.until(EC.text_to_be_present_in_element(
			(By.css_SELECTOR, "#mainsrp-pager > div > div > div > ul.items > li.item.active"), str(page)))
	except Exception as e:
		print(e)
		next_page(page)
	# 當前切換后的頁面的數據
	get_product_info()
 
def main():
	data = get_page_num()
	print('總頁數是=', data)
	for page in range(2, int(data) + 1):
		next_page(page)
 
	# 退出瀏覽器
	driver.quit()
 
if __name__ == '__main__':
	main()

  

 


免責聲明!

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



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