想使用该模块爬点文章,方便绕过代码编写的一些限制,浏览器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 基本写法:
driver = webdriver.Chrome(executable_path=r'./chromedriver94')# driver = webdriver.Firefox(executable_path=r'./geckodriver')driver.get("https://www.baidu.com")# 操作页面节点title = driver.find_element_by_xpath('/html/body/div[3]/div[2]/div[2]/h1')# 获取某节点内容,对html,xml文档的操作还不太熟,都是直接用浏览器F12的右键选取功能,目前还够用title.text

柴2 操作一个已打开的浏览器
借用已登陆的状态及全局的配置(证书,偷懒绕过啦)
需要以可监听方式打开浏览器,注意打开时要先将使用的浏览器窗口全部关闭,否则会失败。
切换到Chrome程序根目录下,在命令行中执行以下指令,随意指定某端口:./Google\ Chrome --remote-debugging-port=12306

主体代码:
其实就是相较于基础版加了一些配置,指定好调试的地址和端口(可以远程调用吗?找机会做个实验)。
from selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsoptions = Options()options.add_experimental_option("debuggerAddress", "127.0.0.1:12306")# 然后在调用的时候加入这个配置。driver = webdriver.Chrome(options=options,executable_path=r'./chromedriver94')
关于options,有其他配置项,可以参考这个文章:https://www.jianshu.com/p/8d2af62c95d2,搜的时候大部分看到的是关于android的,目前没用上,也不影响。
http://npm.taobao.org/mirrors/chromedriver/
工作:
from pathlib import Pathfrom selenium import webdriverimport jsonchrome_option = webdriver.ChromeOptions()chrome_path = r"E:\Download\chromedriver_win32\chromedriver.exe"driver = webdriver.Chrome(executable_path=chrome_path)# 窗口最大化driver.maximize_window()# 打开网页driver.get('http://sso.portal.unicom.local/eip_sso/aiportalLogin.html')print(driver.title)# 元素获取及点击user = '18675521324'password = 'sxxxxxs'# driver.find_element_by_xpath('//*[@id="login"]').click()driver.find_element_by_xpath('//*[@id="login"]').send_keys(user)driver.find_element_by_xpath('//*[@id="password"]').send_keys(password)driver.find_element_by_xpath('//*[@id="login"]').click()cookies = driver.get_cookies()with open("cookies.txt", "w") as fp:json.dump(cookies, fp)driver.quit()
[
