python爬蟲——selenium+firefox使用代理

本文中的知識點:

  • python selenium庫安裝
  • firefox geckodriver的下載與安裝
  • selenium+firefox使用代理
  • 進階學習

搭建開發環境:

PS:安裝了的同學可以跳過了接着下一步,沒安裝的同學還是跟着我的步驟走一遍

安裝selenium庫

pip install selenium

安裝firefox geckodriver

這裏要注意要配置系統環境,把firefox geckodriver解壓後放到python路徑的Scripts目錄下,跟pip在一個目錄下。
這裏可以教大家一個查看python安裝路徑的命令

# windows系統,打開cmd
where python
# linux系統
whereis python

火狐瀏覽器

安裝火狐官方瀏覽器


代碼樣例

以請求百度爲例

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

firefox = webdriver.Firefox()
firefox.get('https://www.baidu.com/')
print(firefox.page_source)
firefox.close()
firefox.quit()

結果如下
在這裏插入圖片描述
在這裏插入圖片描述

使用代理

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

profile = webdriver.FirefoxProfile()
proxy = '42.51.13.68:16816'
ip, port = proxy.split(":")
port = int(port)
# 不使用代理的協議,註釋掉對應的選項即可
settings = {
    'network.proxy.type': 1,  # 0: 不使用代理;1: 手動配置代理
    'network.proxy.http': ip,
    'network.proxy.http_port': port,
    'network.proxy.ssl': ip,  # https的網站,
    'network.proxy.ssl_port': port,
}
# 更新配置文件
for key, value in settings.items():
    profile.set_preference(key, value)
profile.update_preferences()


options = Options()
firefox = webdriver.Firefox(firefox_profile=profile, options=options)
firefox.get('http://dev.kdlapi.com/testproxy')
print(firefox.page_source)
firefox.close()
firefox.quit()
    

運行下,結果如下圖
在這裏插入圖片描述
在這裏插入圖片描述

進階學習

發佈了16 篇原創文章 · 獲贊 21 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章