Python無頭爬蟲下載文件

有些頁面並不能直接用requests獲取到內容,會動態執行一些js代碼生成內容。這個文章主要是對付那些特殊頁面的,好比必需要進行js調用才能下載的狀況。html

安裝chrome

1.wget [https://dl.google.com/linux/direct/google-chrome-stable\_current\_x86\_64.rpm](https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm)
2.yum install ./google-chrome-stable\_current\_x86\_64.rpm
3.yum install mesa-libOSMesa-devel gnu-free-sans-fonts wqy-zenhei-fonts

安裝chromedriver

1.淘寶源(推薦)  
    wget http://npm.taobao.org/mirrors/chromedriver/2.41/chromedriver_linux64.zip
2.unzip chromedriver\_linux64.zip
3.move chromedriver /usr/bin/
4.chmod +x /usr/bin/chromedriver

感謝這篇博客linux

上述步驟能夠選擇適合本身的版本下載,注意:chrome和chrome driver必須是匹配的版本,chrome driver會備註支持的chrome版本號。web

實戰操做

須要引入的庫chrome

from selenium import webdriver
from time import sleep
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException

chrome啓動設置npm

chrome_options = Options()
chrome_options.add_argument('--no-sandbox')#解決DevToolsActivePort文件不存在的報錯
chrome_options.add_argument('window-size=1920x3000') #指定瀏覽器分辨率
chrome_options.add_argument('--disable-gpu') #谷歌文檔提到須要加上這個屬性來規避bug
chrome_options.add_argument('--hide-scrollbars') #隱藏滾動條, 應對一些特殊頁面
chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加載圖片, 提高速度
chrome_options.add_argument('--headless') #瀏覽器不提供可視化頁面. linux下若是系統不支持可視化不加這條會啓動失敗

一樣感謝上面的博客瀏覽器

設置額外參數,好比下載不彈窗和默認下載路徑less

prefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': './filelist'}
chrome_options.add_experimental_option('prefs', prefs)

初始化驅動
cls.driver=webdriver.Chrome(options=chrome_options)ide

退出驅動
cls.driver.quit()ui

請求一個url
cls.driver.get(url)google

執行指定js代碼
cls.driver.execute_script('console.log("helloworld")')

查找指定元素
subtitle = cls.driver.find_element_by_class_name("fubiaoti").text

相關文章
相關標籤/搜索