想使用该模块爬点文章,方便绕过代码编写的一些限制,浏览器cookie、证书配置之类的。

磨刀:

Chromdriver下载:

https://chromedriver.chromium.org/downloads
源站下载:http://chromedriver.storage.googleapis.com/index.html
google官网:https://sites.google.com/a/chromium.org/chromedriver/downloads

Firefox驱动下载:

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

砍柴:

柴1 基本写法:

  1. driver = webdriver.Chrome(executable_path=r'./chromedriver94')
  2. # driver = webdriver.Firefox(executable_path=r'./geckodriver')
  3. driver.get("https://www.baidu.com")
  4. # 操作页面节点
  5. title = driver.find_element_by_xpath('/html/body/div[3]/div[2]/div[2]/h1')
  6. # 获取某节点内容,对html,xml文档的操作还不太熟,都是直接用浏览器F12的右键选取功能,目前还够用
  7. title.text

image.png

柴2 操作一个已打开的浏览器

借用已登陆的状态及全局的配置(证书,偷懒绕过啦)
需要以可监听方式打开浏览器,注意打开时要先将使用的浏览器窗口全部关闭,否则会失败。

  1. 切换到Chrome程序根目录下,在命令行中执行以下指令,随意指定某端口:
  2. ./Google\ Chrome --remote-debugging-port=12306

image.png
主体代码:
其实就是相较于基础版加了一些配置,指定好调试的地址和端口(可以远程调用吗?找机会做个实验)。

  1. from selenium import webdriver
  2. from selenium.webdriver.chrome.options import Options
  3. options = Options()
  4. options.add_experimental_option("debuggerAddress", "127.0.0.1:12306")
  5. # 然后在调用的时候加入这个配置。
  6. driver = webdriver.Chrome(options=options,executable_path=r'./chromedriver94')

关于options,有其他配置项,可以参考这个文章:https://www.jianshu.com/p/8d2af62c95d2,搜的时候大部分看到的是关于android的,目前没用上,也不影响。

http://npm.taobao.org/mirrors/chromedriver/

工作:

  1. from pathlib import Path
  2. from selenium import webdriver
  3. import json
  4. chrome_option = webdriver.ChromeOptions()
  5. chrome_path = r"E:\Download\chromedriver_win32\chromedriver.exe"
  6. driver = webdriver.Chrome(executable_path=chrome_path)
  7. # 窗口最大化
  8. driver.maximize_window()
  9. # 打开网页
  10. driver.get('http://sso.portal.unicom.local/eip_sso/aiportalLogin.html')
  11. print(driver.title)
  12. # 元素获取及点击
  13. user = '18675521324'
  14. password = 'sxxxxxs'
  15. # driver.find_element_by_xpath('//*[@id="login"]').click()
  16. driver.find_element_by_xpath('//*[@id="login"]').send_keys(user)
  17. driver.find_element_by_xpath('//*[@id="password"]').send_keys(password)
  18. driver.find_element_by_xpath('//*[@id="login"]').click()
  19. cookies = driver.get_cookies()
  20. with open("cookies.txt", "w") as fp:
  21. json.dump(cookies, fp)
  22. driver.quit()

[

](https://github.com/mozilla/geckodriver/releases)