爬蟲第五章 selenium模塊的應用

什麼是seleniumphp

selenium是一款基於瀏覽器自動化的模塊

和爬蟲的關聯:
    - 模擬登陸
    - 獲取動態加載的數據

selenium如何獲取動態加載的數據html

環境安裝 : pip install selenium
基本的使用狀況:
    結合着某一款瀏覽器驅動程序實例化一個瀏覽器對象
    1.下載瀏覽器驅動程序:
    http://chromedriver.storage.googleapis.com/index.html
    2.查看驅動和瀏覽器版本的映射關係:
    http://blog.csdn.net/huilan_same/article/details/51896672
    3.編寫自動化操做代碼

實例代碼python

from selenium import webdriver
from bs4 import BeautifulSoup
#實例化一個瀏覽器對象,Chrome能夠選擇成別的瀏覽器,chromedriver.exe是一個可執行程序
bro = webdriver.Chrome(excutable_path='./chromedriver.exe')
#發送get請求
bro.get(url='http://125.35.6.84:81/xk/')
#獲取頁面數據
page_text=bro.page_source
#進行數據解析
soup=BeautifulSoup(page_text,'lxml')
dl_list=soup.select('#gzlist > li > dl')
for dl in dl_list:
    name=dl.string
    print(name)

selenium的詳細用法jquery

bro=webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://www.taobao.com')
#從網頁上定位到搜索框,並輸入信息 search_input
=bro.find_element_by_id('q') search_input.send_keys('小蘋果') time.sleep(2) #如何執行js代碼 bro.execute_script('window.scrollTo(0,document.body.scrollHeight)') time.sleep(2) bro.execute_script('window.scrollTo(0,document.body.scrollHeight)') time.sleep(2) #定位到提交按鈕,輸入完畢以後點擊提交 btn = bro.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button') btn.click() time.sleep(2) #關閉瀏覽器 bro.quit()

執行動做鏈(執行動做鏈其實就是拖動某一個物體到另外一個地方)web

 

實例代碼chrome

from selenium import webdriver
frim selenium.webdriver import ActionChains

# 實例化一個瀏覽器頁面
bro = webdriver.Chrome(executable_path='chromedriver.exe')
# 向這個網址發送請求
bro.get('https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
# 若是html中又封裝了一個html,則須要手動找到iframe標籤 ,須要在定位到這個標籤才能夠
bro.switch_to.frame('iframeResult')
# 找到拖拉窗口的標籤
div_tag = bro.find_element_by_id('draggable')
# 實例化一個動做鏈對象,將整個頁面頁面所有傳遞進去
actionChains = ActionChains(bro)
# 給動做鏈對象指定那個標籤進行拖拽
actionChains.click_and_hold(div_tag)

# 指定拖動幾回
for i in range(3):
    # 指定每一次拖動的距離
    actionChains.move_by_offset(40, 0).perform()
    time.sleep(1)

# 動做鏈的釋放
actionChains.release()
# 退出瀏覽器
bro.quit()
咱們如今知道了selenium能夠垂手可得的爬取到網站的動態數據,那麼有些網站就會出來檢測你所發送的請求是否是selenium模塊發送的,若是是,直接屏蔽掉,那麼咱們就沒法獲取到數據了

 解決方法:json

#固定用法
from
selenium.webdriver import ChromeOptions option = ChromeOptions() option.add_experimental_option('excludeSwitches', ['enable-automation']) url = 'https://bj.meituan.com/' bro = webdriver.Chrome(executable_path='./chromedriver.exe',options=option) bro.get(url) time.sleep(2) bro.get(url)
如何設置瀏覽器的無可視化界面
from selenium.webdriver.chrome.options import Options

# 建立一個參數對象,用來控制chrome以無界面模式打開
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
url = 'https://bj.meituan.com/'
bro = webdriver.Chrome(executable_path='./chromedriver.exe', chrome_options=chrome_options)
bro.get(url)
time.sleep(2)
bro.get(url)
time.sleep(2)
bro.save_screenshot('1.png')
print(bro.page_source)

scrapy框架api

概況:瀏覽器

什麼是框架: 
    框架實際上是一個具備很強的通用性而且集成了不少功能的項目模板

如何學習框架:
    掌握框架的功能,能夠熟練使用每一種功能便可.

scrapy:
    - 集成了異步操做,高性能的數據解析,高性能的持久化存儲

環境的安裝:app

1. pip install wheel

2. 下載twisted  http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted

3. 在python的Teminal中進入下載的目錄,執行pip3 install Twisted‑17.1.0‑cp36‑cp36m‑win_amd64.whl

4. pip3 install pywin32

5. pip3 install scrapy

使用流程:

1.建立一個工程:(建立完成以後會出現一個項目的目錄) scrapy startproject ProName

2.cd 到ProName

3.建立一個爬蟲文件: (建立完成以後會在項目目錄下的spiders目錄下出現一個爬蟲文件)

  scrapy genspider spiderName www.baibai.com

 

 

而後在爬蟲文件中會出現如下代碼

name : 爬蟲文件的名稱

allowed_domains : 容許經過的域名(通常用不到,除非排除的時候)

start_urls : 至關於全部的域名

而後咱們進入settings.py文件中進行配置:

4.執行程序 : 

  scrapy crawl spiderName

實例: 12306模擬登陸

超級鷹代碼識別驗證碼:

import requests
from hashlib import md5

class Chaojiying_Client(object):

    def __init__(self, username, password, soft_id):
        self.username = username
        password =  password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: 圖片字節
        codetype: 題目類型 參考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:報錯題目的圖片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()

def get_img_text(imgPath):
    chaojiying = Chaojiying_Client('超級鷹帳號', '超級鷹密碼', '899370')#用戶中心>>軟件ID 生成一個替換 96001
    im = open(imgPath, 'rb').read()#本地圖片文件路徑 來替換 a.jpg 有時WIN系統需要//
    return chaojiying.PostPic(im, 9004)['pic_str']

而後對12306進行模擬登陸: 驗證碼圖片必須經過裁剪圖片的形式獲取

from selenium import webdriver
from lxml import etree
from selenium.webdriver import ActionChains
from PIL import Image
from time import sleep

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://kyfw.12306.cn/otn/login/init')
sleep(2)
bro.find_element_by_id('username').send_keys('xxxxxxx')
bro.find_element_by_id('password').send_keys('123456')

#想要獲取驗證碼圖片左上角和右下角亮點座標,經過這亮點座標能夠造成一個裁剪的矩形區域
code_img_ele = bro.find_element_by_xpath('//*[@id="loginForm"]/div/ul[2]/li[4]/div/div/div[3]/img')
location = code_img_ele.location  # 驗證碼圖片左上角座標
size = code_img_ele.size #驗證碼圖片的長寬
#指定矩形區域
rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']))

bro.save_screenshot('aa.png')

i = Image.open('./aa.png')
code_img_name = 'code.png'
frame = i.crop(rangle)
frame.save(code_img_name)
#進行驗證碼的識別
result = get_img_text(code_img_name)
print(result)
# x1,y1|x2,y2|x3,y3                   x,y
#[[x1,y1],[x2,y2],[x3,y3]]            [[x,y]]
all_list = []
if '|' in result:
    list_1 = result.split('|')
    count_1 = len(list_1)
    for i in range(count_1):
        xy_list = []
        x = int(list_1[i].split(',')[0])
        y = int(list_1[i].split(',')[1])
        xy_list.append(x)
        xy_list.append(y)
        all_list.append(xy_list)
else:
    x = int(result.split(',')[0])
    y = int(result.split(',')[1])
    xy_list = []
    xy_list.append(x)
    xy_list.append(y)
    all_list.append(xy_list)

for l in all_list:
    #x,y就是須要點擊的某一個點的座標
    x = l[0]
    y = l[1]
    #move_to_element_with_offset就是將x,y的參照系轉移到指定的標籤中
    #每個動做連的操做都必須基於一個單獨的動做連
    ActionChains(bro).move_to_element_with_offset(code_img_ele,x,y).click().perform()

sleep(2)

bro.find_element_by_id('loginSub').click()
sleep(10)

bro.quit()
相關文章
相關標籤/搜索