溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python爬蟲實戰(zhàn)1-解決需要爬取網(wǎng)頁N秒后的內(nèi)容的需求

發(fā)布時間:2020-03-23 14:16:49 來源:網(wǎng)絡 閱讀:1408 作者:小生博客 欄目:大數(shù)據(jù)

小生博客:http://xsboke.blog.51cto.com

                        -------謝謝您的參考,如有疑問,歡迎交流

前引:

    當你需要爬取的頁面內(nèi)容在訪問頁面5秒后才會出現(xiàn),
    這時使用python的requests模塊就很難爬取到你想要的內(nèi)容了.

    requests和selenium的不同:
        requests是通過模擬http請求來實現(xiàn)瀏覽網(wǎng)頁的
        selenuim是通過瀏覽器的API實現(xiàn)控制瀏覽器,從而達到瀏覽器自動化

    上面說了,selenium是通過控制瀏覽器實現(xiàn)訪問的,但是linux的命令行是不能打開瀏覽器的,
    幸運的是Chrome和Firefox有一個特殊的功能headless(無頭)模式.(就是wujie面模式)
    通過headless模式可以實現(xiàn)在linux命令行控制瀏覽器。

    接下來要實現(xiàn)的就是在linux命令行界面通過Chrome的headless模式,實現(xiàn)獲取訪問網(wǎng)頁5秒后的內(nèi)容

一. 環(huán)境準備

    1. 安裝谷歌瀏覽器linux版及其依賴包.

        [root@localhost ~]# wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
        [root@localhost ~]# yum localinstall google-chrome-stable_current_x86_64.rpm --nogpgcheck

    2. 下載selenium連接chrome的驅(qū)動程序(要下載和chrome對應的版本).
        [root@localhost ~]# google-chrome --version
        Google Chrome 72.0.3626.109 
        [root@localhost ~]# https://chromedriver.storage.googleapis.com/72.0.3626.69/chromedriver_linux64.zip
        [root@localhost ~]# unzip chromedriver_linux64.zip
        [root@localhost ~]# chmod +x chromedrive

    3.  安裝python需要模塊
        # beautifulsoup4是一個html,xml解析器
        [root@localhost ~]# pip install beautifulsoup4 selenium

二. 開始實現(xiàn)獲取網(wǎng)頁5秒后的數(shù)據(jù)

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import time

from bs4 import BeautifulSoup
from selenium import webdriver

opt = webdriver.ChromeOptions()          # 創(chuàng)建chrome對象
opt.add_argument('--no-sandbox')          # 啟用非沙盒模式,linux必填,否則會報錯:(unknown error: DevToolsActivePort file doesn't exist)......
opt.add_argument('--disable-gpu')          # 禁用gpu,linux部署需填,防止未知bug
opt.add_argument('headless')          # 把chrome設置成wujie面模式,不論windows還是linux都可以,自動適配對應參數(shù)
driver = webdriver.Chrome(executable_path=r'/root/chromedriver',options=opt)    # 指定chrome驅(qū)動程序位置和chrome選項
driver.get('https://baidu.com')          # 訪問網(wǎng)頁
time.sleep(5)           # 等待5秒
content = driver.page_source          # 獲取5秒后的頁面
soup = BeautifulSoup(content,features='html.parser')    # 將獲取到的內(nèi)容轉(zhuǎn)換成BeautifulSoup對象
driver.close()

print(soup.body.get_text())          # 通過BeautifulSoup對象訪問獲取到的頁面內(nèi)容
向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI