selenium常用操作
使用无界面浏览器
Selenium+Headless Firefox
Selenium+Headless Firefox和Selenium+Firefox,区别就是实例option的时候设置-headless参数。
前提条件:
- 本地安装Firefox浏览器
- 本地需要geckodriver驱动器文件,如果不配置环境变量的话,需要手动指定executable_path参数。
from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options def main(): options = Options() options.add_argument('-headless') driver = Firefox(executable_path='./geckodriver', firefox_options=options) driver.get("https://www.qiushibaike.com/8hr/page/1/") print(driver.page_source) driver.close() if __name__ == '__main__': main()
Selenium+Headless Chrome
与Firefox
类似,双手奉上。
前提条件:
- 本地安装Chrome浏览器
- 本地需要chromedriver驱动器文件,如果不配置环境变量的话,需要手动指定executable_path
参数。
from selenium import webdriver from selenium.webdriver.chrome.options import Options def main(): chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') driver = webdriver.Chrome(executable_path='./chromedriver', chrome_options=chrome_options) driver.get("https://www.baidu.com") print(driver.page_source) driver.close() if __name__ == '__main__': main()
Selenium+Headless Edge
安装Edge浏览器
下载Edge驱动:Microsoft Edge Driver - Microsoft Edge Developer
安装edge相关包
pip install msedge-selenium-tools
示例
from msedge.selenium_tools import EdgeOptions from msedge.selenium_tools import Edge options = EdgeOptions() options.use_chromium = True # if we miss this line, we can't make Edge headless # A little different from Chrome cause we don't need two lines(--) before 'headless' and 'disable-gpu' options.add_argument('headless') options.add_argument('disable-gpu') browser = Edge(executable_path='msedgedriver', options=options) browser.get('https://www.baidu.com')