Python無頭爬蟲下載文件的實(shí)現(xiàn)
有些頁面并不能直接用requests獲取到內(nèi)容,會動態(tài)執(zhí)行一些js代碼生成內(nèi)容。這個文章主要是對付那些特殊頁面的,比如必須要進(jìn)行js調(diào)用才能下載的情況。
安裝chrome
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)yum install ./google-chrome-stable_current_x86_64.rpmyum install mesa-libOSMesa-devel gnu-free-sans-fonts wqy-zenhei-fonts
安裝chromedriver
淘寶源(推薦)
wget http://npm.taobao.org/mirrors/chromedriver/2.41/chromedriver_linux64.zipunzip chromedriver_linux64.zipmove chromedriver /usr/bin/chmod +x /usr/bin/chromedriver
感謝這篇博客
上述步驟可以選擇適合自己的版本下載,注意:chrome和chrome driver必須是匹配的版本,chrome driver會備注支持的chrome版本號。
實(shí)戰(zhàn)操作
需要引入的庫
from selenium import webdriverfrom time import sleepfrom selenium.webdriver.chrome.options import Optionsfrom selenium.common.exceptions import NoSuchElementException
chrome啟動設(shè)置
chrome_options = Options()chrome_options.add_argument(’--no-sandbox’)#解決DevToolsActivePort文件不存在的報(bào)錯chrome_options.add_argument(’window-size=1920x3000’) #指定瀏覽器分辨率chrome_options.add_argument(’--disable-gpu’) #谷歌文檔提到需要加上這個屬性來規(guī)避bugchrome_options.add_argument(’--hide-scrollbars’) #隱藏滾動條, 應(yīng)對一些特殊頁面chrome_options.add_argument(’blink-settings=imagesEnabled=false’) #不加載圖片, 提升速度chrome_options.add_argument(’--headless’) #瀏覽器不提供可視化頁面. linux下如果系統(tǒng)不支持可視化不加這條會啟動失敗
同樣感謝上面的博客
設(shè)置額外參數(shù),比如下載不彈窗和默認(rèn)下載路徑
prefs = {’profile.default_content_settings.popups’: 0, ’download.default_directory’: ’./filelist’}chrome_options.add_experimental_option(’prefs’, prefs)
初始化驅(qū)動
cls.driver=webdriver.Chrome(options=chrome_options)
退出驅(qū)動
cls.driver.quit()
請求一個url
cls.driver.get(url)
執(zhí)行指定js代碼
cls.driver.execute_script(’console.log('helloworld')’)
查找指定元素
subtitle = cls.driver.find_element_by_class_name('fubiaoti').text
到此這篇關(guān)于Python無頭爬蟲下載文件的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python無頭爬蟲下載文件內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. HTML實(shí)現(xiàn)title 屬性換行小技巧2. ASP.NET MVC實(shí)現(xiàn)單個圖片上傳、限制圖片格式與大小并在服務(wù)端裁剪圖片3. python基于tkinter制作無損音樂下載工具(附源碼)4. Java 獲取 jar包以外的資源操作5. js中textContent、innerText和innerHTML的用法以及區(qū)別6. python 利用 PIL 將數(shù)組值轉(zhuǎn)成圖片的實(shí)現(xiàn)7. Python3 assert斷言實(shí)現(xiàn)原理解析8. 在Vue中創(chuàng)建可重用的 Transition的方法9. Python CSS選擇器爬取京東網(wǎng)商品信息過程解析10. python中的裝飾器該如何使用
