1. 程式人生 > 實用技巧 >python+selenium動態抓取網頁資料

python+selenium動態抓取網頁資料

window+python+selenium

1.下載selenium

cmd pip3 instatll selenium

2.下載瀏覽器對應驅動版本

檢視瀏覽器版本:chrome://version

驅動下載國外連線:http://chromedriver.storage.googleapis.com/index.html

驅動下載國內映象連線(推薦):http://npm.taobao.org/mirrors/chromedriver/

把此驅動放在python安裝目錄,與phthon.exe同級

程式碼測試

from selenium import webdriver
'''
@Author: 馬家立
@Date: 2020/12/22 17:00
@Description: 延時抓取動態網頁資料(基於scrapy)
''' print("開始爬取資料...") option = webdriver.ChromeOptions() # “no-sandbox”: 沙盒模式執行,以最高許可權執行 option.add_argument('-no-sandbox') # 大量渲染時候寫入/tmp而非/dev/shm option.add_argument('-disable-dev-shm-usage') # “headless”:不用開啟圖形介面,若註釋則會開啟瀏覽器 option.add_argument('-headless') # 不載入圖片, 提升速度 option.add_argument('-blink-settings=imagesEnabled=false
') # 谷歌文件提到需要加上這個屬性來規避bug option.add_argument('-disable-gpu') # 指定驅動路徑 browser = webdriver.Chrome(options=option) # 訪問百度 browser.get('http://www.baidu.com/') # 列印標題 print(browser.title) # 關閉瀏覽器 browser.quit()

Ps:ChromeOptions詳情可見:https://www.jianshu.com/p/8ec70859ae03

Linux+python+selenium

1.下載selenium

pip3 instatll selenium

2.安裝chrome

Linux 命令安裝最新的 Google Chrome

yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm

或者下載到本地再安裝

wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum install ./google-chrome-stable_current_x86_64.rpm

安裝必要的庫

yum install mesa-libOSMesa-devel gnu-free-sans-fonts wqy-zenhei-fonts

3、安裝 chromedriver

Linux命令檢視谷歌瀏覽器版本

google-chrome --version

Window下驅動下載:

驅動下載國外連線:http://chromedriver.storage.googleapis.com/index.html

驅動下載國內映象連線(推薦):http://npm.taobao.org/mirrors/chromedriver/

將下載好的Linux下chrome對應驅動上傳至Linux伺服器上

推薦放在/usr/bin目錄下:

/usr/bin/chromedriver

給予執行許可權

chmod +x /usr/bin/chromedriver

配置環境變數

export PATH=$PATH:/usr/bin/chromedriver/