本文旨在記錄selenium的一些操做實例,沒啥技術含量,也沒有太多概念的內容。html
pip install selenium
下載前須要確認適配本身的瀏覽器版本python
https://chromedriver.storage.googleapis.com/index.htmlweb
基本用法看官方文檔,講述的很清楚了,推薦chrome
https://selenium-python.readthedocs.io/installation.html
設置瀏覽器不加載圖片api
from selenium import webdriver # 設置不加載圖片 chrome_opt = webdriver.ChromeOptions() prefs = { "profile.managed_default_content_settings.images": 2 } chrome_opt.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(chrome_options=chrome_opt) driver.get("https://www.taobao.com")
點擊彈窗與點擊下拉列表瀏覽器
from selenium import webdriver from selenium.webdriver.support.select import Select driver = webdriver.Chrome() # 點擊接受彈窗 driver.switch_to.alert.accept() # 點擊下拉列表 sel = driver.find_element_by_id("nr") Select(sel).select_by_index(2)
切換窗口cookie
from selenium import webdriver driver = webdriver.Chrome() first_win = driver.current_window_handle all_win = driver.current_window_handle for win in all_win: if win != first_win: driver.switch_to.window(win)
自動下拉列表(以開源中國的博客欄目爲例)session
不少頁面是下拉加載更多信息,咱們如何模擬這個下拉操做:dom
from selenium import webdriver import time driver = webdriver.Chrome() driver.get('https://www.oschina.net/blog') time.sleep(5) # 實現自動下拉刷新 下拉三頁 for i in range(3): driver.execute_script('window.scrollTo(0,document.body.scrollHeight); var lenOfPage=document.body.scrollHeight; return lenOfPage;') time.sleep(3)
如何模擬手機訪問?scrapy
from selenium import webdriver # 模擬手機 mobilesetting = {"deviceName":"iPhone 6 Plus"} options = webdriver.ChromeOptions() options.add_experimental_option("mobileEmulation", mobilesetting) driver = webdriver.Chrome(chrome_options=options) # 設置大小 driver.set_window_size(400, 800) # driver.maximize_window() driver.get("https://www.taobao.com") # 後退 driver.back() # 前進 driver.forward() # 刷新 driver.refresh()
如何爲selenium設置代理?(鏈接無用戶名密碼認證的代理)
設置代理 from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument("--proxy-server=http://ip:port") driver = webdriver.Chrome(chrome_options=options) driver.get("http://httpbin.org/ip") print(driver.page_source)
如何爲selenium設置代理?(有用戶名和密碼的鏈接)
推薦幾篇文章:
https://www.cnblogs.com/roystime/p/6935543.html https://stackoverflow.com/questions/29983106/how-can-i-set-proxy-with-authentication-in-selenium-chrome-web-driver-using-pyth#answer-30953780 https://cuiqingcai.com/4880.html
scrapy + selenium 模擬登陸csdn
其實,沒啥技術含量。只是簡單運用,敲一遍加深印象。
關於selenium的基礎用法強烈建議用的時候看下文檔就好,技術含量不高,無需過多費心。
spider.py
# -*- coding: utf-8 -*- import scrapy from selenium import webdriver class CsdnSpider(scrapy.Spider): name = 'csdn' allowed_domains = ['csdn.net'] start_urls = ['https://passport.csdn.net/account/login','https://i.csdn.net/#/account/index'] def __init__(self): # mobilsetting = {"deviceName":"iPhone 6 Plus"} # options = webdriver.ChromeOptions() # options.add_experimental_option("mobileEmulation", mobilsetting) self.browser = None self.cookies = None # self.browser.set_window_size(400,800) super(CsdnSpider, self).__init__() def spider_closed(self, response): print("spider close") self.brower.close() def parse(self, response): print(response.url) print(response.body.decode("utf-8","ignore"))
middlewares.py
from scrapy import signals from selenium import webdriver from scrapy.http import HtmlResponse import time import requests class LoginMiddleware(object): def process_request(self, request, spider): if spider.name == "csdn": if request.url.find("login") != -1: spider.browser = webdriver.Chrome() spider.browser.get(request.url) switch = spider.browser.find_element_by_xpath('//a[@class="login-code__open js_login_trigger login-user__active"]') if switch.text == '帳號登陸': switch.click() time.sleep(3) username = spider.browser.find_element_by_id('username') password = spider.browser.find_element_by_id('password') time.sleep(2) username.send_keys("") time.sleep(1) password.send_keys("") time.sleep(2) click = spider.browser.find_element_by_class_name("logging") time.sleep(2) click.click() time.sleep(8) spider.cookies = spider.browser.get_cookies() return HtmlResponse( url=spider.browser.current_url, body=spider.browser.page_source, encoding="utf-8" ) else: req = requests.session() for cookie in spider.cookies: req.cookies.set(cookie['name'], cookie['value']) req.headers.clear() newpage = req.get(request.url) print(request.url) print(newpage.text) return HtmlResponse( url=request.url, body=newpage.text, encoding="utf-8" )