Python無(wú)頭爬蟲下載文件的實(shí)現(xiàn)
有些頁(yè)面并不能直接用requests獲取到內(nèi)容,會(huì)動(dòng)態(tài)執(zhí)行一些js代碼生成內(nèi)容。這個(gè)文章主要是對(duì)付那些特殊頁(yè)面的,比如必須要進(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會(huì)備注支持的chrome版本號(hào)。
實(shí)戰(zhàn)操作
需要引入的庫(kù)
from selenium import webdriverfrom time import sleepfrom selenium.webdriver.chrome.options import Optionsfrom selenium.common.exceptions import NoSuchElementException
chrome啟動(dòng)設(shè)置
chrome_options = Options()chrome_options.add_argument(’--no-sandbox’)#解決DevToolsActivePort文件不存在的報(bào)錯(cuò)chrome_options.add_argument(’window-size=1920x3000’) #指定瀏覽器分辨率chrome_options.add_argument(’--disable-gpu’) #谷歌文檔提到需要加上這個(gè)屬性來(lái)規(guī)避bugchrome_options.add_argument(’--hide-scrollbars’) #隱藏滾動(dòng)條, 應(yīng)對(duì)一些特殊頁(yè)面chrome_options.add_argument(’blink-settings=imagesEnabled=false’) #不加載圖片, 提升速度chrome_options.add_argument(’--headless’) #瀏覽器不提供可視化頁(yè)面. linux下如果系統(tǒng)不支持可視化不加這條會(huì)啟動(dòng)失敗
同樣感謝上面的博客
設(shè)置額外參數(shù),比如下載不彈窗和默認(rèn)下載路徑
prefs = {’profile.default_content_settings.popups’: 0, ’download.default_directory’: ’./filelist’}chrome_options.add_experimental_option(’prefs’, prefs)
初始化驅(qū)動(dòng)
cls.driver=webdriver.Chrome(options=chrome_options)
退出驅(qū)動(dòng)
cls.driver.quit()
請(qǐng)求一個(gè)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無(wú)頭爬蟲下載文件的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python無(wú)頭爬蟲下載文件內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. PHP如何打印跟蹤調(diào)試信息2. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析3. HTML DOM setInterval和clearInterval方法案例詳解4. XML入門的常見(jiàn)問(wèn)題(二)5. HTML <!DOCTYPE> 標(biāo)簽6. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)7. HTML5 Canvas繪制圖形從入門到精通8. 小技巧處理div內(nèi)容溢出9. 匹配模式 - XSL教程 - 410. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼
