Python爬蟲_selenium + Firefox的使用


驅動下載:http://chromedriver.storage.googleapis.com/index.html

https://github.com/mozilla/geckodriver/releases

 

一、selenium啟動Firefox瀏覽器。


1
from selenium import webdriver 2 # from selenium.webdriver.firefox.firefox_profile import FirefoxProfile 3 4 5 user_agent = 'Mozilla/5.0 (Linux; Android 7.0; BND-AL10 Build/HONORBND-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/044304 Mobile Safari/537.36 MicroMessenger/6.7.3.1340(0x26070331) NetType/4G Language/zh_CN Process/tools' 6 7 proxy = '127.0.0.1:5000' 8 proxy = proxy.split(':') 9 10 11 # selenium headless 啟動無頭模式 12 options = webdriver.FirefoxOptions() 13 options.add_argument('-headless') 14 15 16 # 第一步:創建一個FirefoxProfile實例 17 profile = webdriver.FirefoxProfile() 18 # 第二步:開啟“手動設置代理” 19 profile.set_preference('network.proxy.type',1) 20 # 第三步:設置代理IP 21 profile.set_preference('network.proxy.http', proxy[0]) 22 # 第四步:設置代理端口,注意端口是int類型,不是字符串 23 profile.set_preference('network.proxy.http_port', int(proxy[1])) 24 25 # 第五步:設置htpps協議也使用該代理 26 # profile.set_preference('network.proxy.ssl', proxy[0]) 27 # profile.set_preference('network.proxy.ssl_port', proxy[1]) 28 29 # 第六步:所有協議共用一種 ip 及端口,如果單獨配置,不必設置該項,因為其默認為 False 30 profile.set_preference("network.proxy.share_proxy_settings", True) 31 # 第七步:設置請求header 32 profile.set_preference("general.useragent.override", user_agent) 33 34 # 默認本地地址(localhost)不使用代理,如果有些域名在訪問時不想使用代理可以使用類似下面的參數設置 35 # profile.set_preference("network.proxy.no_proxies_on", "localhost") 36 37 38 # 以代理方式啟動 firefox 39 firefox = webdriver.Firefox(profile,executable_path='/opt/geckodriver',options=options) 40 42 firefox.get('http://www.baidu.com') 43 44 45 # 退出 46 firefox.quit()

 二、設置加載超時處理。

1.  pageLoadTimeout;

pageLoadTimeout方法用來設置頁面完全加載的超時時間,完全加載即頁面全部渲染,異步同步腳本都執行完成。沒有設置超時時間默認是等待頁面全部加載完成才會進入下一步驟,設置超時時間3s是加載到3s時中斷操作拋出異常;

driver.manage().timeouts().setScriptTimeout(3,TimeUnit.SECONDS);

2.  setScriptTimeout
設置異步腳本到超時時間,用法同pageLoadTimeout一樣,異步腳本也就是有async屬性的異步腳本,可以在頁面解析的同時執行;
(我一般會使用這個解決讀取超時問題,用pageLoadTimeout不知道為什么不起作用)

3.  implicitlyWait
識別對象的超時時間,如果在設置的時間內沒有找到就拋出一個NoSuchElement異常,用法參數和上述一樣;

4. driver.set_page_load_timeout

使用selenium爬取人大經濟論壇,登陸的時候,頁面一直不加載完成,一直在刷新,應該是強制登陸頁面一直刷新。
用webdrive的get方法,只能在頁面加載完成后才能后續操作,所以,設置了強制加載時間。
這個設置會拋出一個timeout錯誤,使用pass處理后,繼續后邊的操作。
后面的操作里又要在webdriver的返回值里查找,
查找的時候,又拋出異常

driver = webdriver.Chrome()
driver.set_page_load_timeout(10)

try:
    driver.get('http://bbs.pinggu.org/plugin.php?id=dsu_paulsign:sign')
except:    # 異常處理
    pass                # 當頁面加載時間超過設定時間,執行后續動作

 

三:selenium啟動Chrome瀏覽器。

def init_chrom():
    display_size = ['800,1200', '1024,600', '1024,768', '1024,1536', '1152,864', '1152,1728', '1280,720',
                    '1280,768', '1280,800', '1280,900', '1280,960', '1280,1024', '1280,1600', '1280,2048',
                    '1360,768', '1360,1024', '1400,1050', '1400,2100', '1440,900', '1600,1024', '1600,1200',
                    '1600,2400', '1680,1050', '1792,1344', '1800,1440']
    chrome_options = webdriver.ChromeOptions()
    # 在root權限下運行
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    # 無界面模式
    # chrome_options.add_argument('--headless')
    # 解決有時定位會出現問題
    chrome_options.add_argument('--disable-gpu')
    # 無痕跡模式
    chrome_options.add_argument('--incognito')
    chrome_options.add_argument('user-agent=' + Ua().random)
    # 設置窗口不顯示‘自動化測試’提示
    chrome_options.add_argument('--disable-infobars')
    chrome_options.add_argument('window-size=' + choice(display_size))
    # 禁用自動化欄# 禁用“禁用開發人員模式擴展”彈出窗口
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation', 'load-extension']) chrome_options.add_argument(
'blink-settings=imagesEnabled=false') # 設置不顯示圖片 chrome_options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2}) # 設置不顯示圖片 driver = webdriver.Chrome(executable_path="/opt/chromedriver", options=chrome_options) driver.implicitly_wait(10) # 頁面加載最大時間 driver.set_page_load_timeout(20) driver.get('http://www.baidu.com') return True

 

# """
# class屬性唯一但是有空格,選擇空格兩邊唯一的那一個
# 若空格隔開的class不唯一可以通過索引進行定位
# self.driver.find_elements_by_class_name('table-dragColumn')[0].click()
# 通過css方法進行定位(空格以‘.’代替)
# options.add_argument('--disable-infobars')  # 禁止策略化
# options.add_argument('--no-sandbox')  # 解決DevToolsActivePort文件不存在的報錯
# options.add_argument('window-size=1920x3000')  # 指定瀏覽器分辨率
# options.add_argument('--disable-gpu')  # 谷歌文檔提到需要加上這個屬性來規避bug
# options.add_argument('--incognito')  # 隱身模式(無痕模式)
# options.add_argument('--disable-javascript')  # 禁用javascript
# options.add_argument('--start-maximized')  # 最大化運行(全屏窗口),不設置,取元素會報錯
# options.add_argument('--hide-scrollbars')  # 隱藏滾動條, 應對一些特殊頁面
# options.add_argument('blink-settings=imagesEnabled=false')  # 不加載圖片, 提升速度
# options.add_argument('--headless')  # 瀏覽器不提供可視化頁面. linux下如果系統不支持可視化不加這條會啟動失敗
# options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  # 手動指定使用的瀏覽器位置
# options.add_argument('lang=en_US') # 設置語言
# options.add_argument('User-Agent=Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36')
# options.add_argument('--headless')  # 瀏覽器不提供可視化頁面
# prefs = {"":""}
# prefs["credentials_enable_service"] = False
# prefs["profile.password_manager_enabled"] = False
# chrome_option_set.add_experimental_option("prefs", prefs) # 屏蔽'保存密碼'提示框

 

 

pyppeteer代替selenium繞過webdriver檢測,參考鏈接:https://www.cnblogs.com/chenhuabin/p/10989895.html

selenium同類型的工具pyppeteer的使用:https://mp.weixin.qq.com/s?__biz=MzIzNzA4NDk3Nw==&mid=2457737358&idx=1&sn=fb88904cac67300130cabbc72bc4a650&chksm=ff44b0d0c83339c6496cabf8e09e8a9e0316df1032ef7523ba6ab7f4f6a4bea1cd4c02eb7d7b&mpshare=1&scene=1&srcid=&key=076402fec4624ccbe758d20c86fbbfabff1a1de62190662a69bb6decd76681b07d9b48c371a99b1237702740a0181d36410e1af661dad8732cc0c65b9f772fb3f988ce1840a07037579a9d134d7ad57d&ascene=1&uin=MjU5MjA4OTg0NA%3D%3D&devicetype=Windows+10&version=62060739&lang=zh_CN&pass_ticket=gFs%2B1sVN%2FxqIhOn1175cxFLsbS1MTzKJWqgpBIPWD9ilQcFn2fWqjXZ1AlHSt0fh

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM