当前位置:   article > 正文

Selenium隐藏浏览器页面

selenium隐藏浏览器

Selenium隐藏浏览器页面

背景

在工作,学习中,我们常常会使用selenium来获取网页上的数据,编完完整程序之后,实现真正意义上的自动化获取,此时我们会发现在运行中往往会弹出浏览器页面,在调试过程中,这很方便,但是跑自动化时,我们就需要将浏览器隐藏在后台运行即可。这样就不会影响其他工作的进行。

方法

主要是通过修改浏览器启动选项进行设置,其实就是将driver=webdriver.Chrome()换成一下三行代码即可,涉及代码如下:

#浏览器启动选项
option=webdriver.ChromeOptions()
#指定为无界面模式
option.add_argument('--headless')
# option.headless=True  或者将上面的语句换成这条亦可
#创建Chrome驱动程序的实例
driver=webdriver.Chrome(options=option)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

下面通过实例来展示,实现结果:

弹出浏览器页面

在这里我列出一个我认为不错的方法,分享给小伙伴们:
首先,是不隐藏浏览器的正常写法如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
url='https://www.baidu.com/'
#创建Chrome驱动程序的实例
driver=webdriver.Chrome()
#打开浏览器并获取此网址的信息
driver.get(url)
#根据定位条件定位内容,并输出
content=driver.find_element(By.XPATH,'//*[@id="s-top-left"]/a[1]')
print(content.text)
#关闭浏览器
driver.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

运行结果如下:此时是有浏览器页面弹出的。

D:\workplace\venv\Scripts\python.exe D:\workplace\venv\111.py 
新闻

Process finished with exit code 0
  • 1
  • 2
  • 3
  • 4
在后台隐藏浏览器页面

通过修改浏览器启动选项,来设置浏览器的显隐:

from selenium import webdriver
from selenium.webdriver.common.by import By
url='https://www.baidu.com/'
#浏览器启动选项
option=webdriver.ChromeOptions()
#添加启动选项,指定为无界面模式
option.add_argument('--headless')
# option.headless=True  或者将上面的语句换成这条亦可
#创建Chrome驱动程序的实例
driver=webdriver.Chrome(options=option)
#,打开浏览器并获取此网址的信息
driver.get(url)
#根据定位条件定位内容,并输出
content=driver.find_element(By.XPATH,'//*[@id="s-top-left"]/a[1]')
print(content.text)
#关闭浏览器
driver.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

运行结果如下,此时浏览器页面无弹出。

D:\workplace\venv\Scripts\python.exe D:\workplace\venv\111.py 
新闻

Process finished with exit code 0
  • 1
  • 2
  • 3
  • 4

总结

掌握一门技术的最佳途径就是实践,好记性不如烂笔头,让咱们一起去实践学习吧!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/626544
推荐阅读
相关标签
  

闽ICP备14008679号