search
HomeBackend DevelopmentPython TutorialPython implements randomly calling a browser to open a web page

下面为大家分享一篇python实现随机调用一个浏览器打开网页,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧

前两天总结了一下python爬虫 使用真实浏览器打开网页的两种方法总结

但那仅仅是总结一下而已,今天本文来实战演练一下

依然使用的是 webbrowser 这个模块 来调用浏览器

关于的三种打开方式在上一篇文章中已经说过了,这里不再赘述

如果没有特意注册,那么将会是使用默认的浏览器来打开网页,如下:

#默认浏览器 
#coding:utf-8 
import webbrowser as web #对导入的库进行重命名 
def run_to_use_default_browser_open_url(url): 
 web.open_new_tab(url) 
 print 'run_to_use_default_browser_open_url open url ending ....'

真正的注册一个非默认浏览器:

这里先用的firfox浏览器

#firefox浏览器 
def use_firefox_open_url(url): 
 browser_path=r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe' 
 #这里的‘firefox'只是一个浏览器的代号,可以命名为自己认识的名字,只要浏览器路径正确 
 web.register('firefox', web.Mozilla('mozilla'), web.BackgroundBrowser(browser_path)) 
 #web.get('firefox').open(url,new=1,autoraise=True) 
 web.get('firefox').open_new_tab(url) 
 print 'use_firefox_open_url open url ending ....'

解释一下这个注册函数当前的用法

web.register() 它的三个参数

第一个为 自己给浏览器重新命的名字, 主要目的是为了在之后的调用中,使用者能够找到它

第二个参数, 可以按照这样上面的例子这样写,因为python本身将一些浏览器实例化了, 但是还是推荐 将其赋值为 None ,因为这个参数没有更好,毕竟有些浏览器python本身并没有实例化,而这个参数也不影响它的使用

第三个参数,目前所知是浏览器的路径, 不知道有没有别的写法

当然,这里只是在这里的用法, 函数本身的意思可以去源文件中查看

下面给我一些测试的实例:

#coding:utf-8
import webbrowser as web #对导入的库进行重命名
import os
import time
#默认浏览器
def run_to_use_default_browser_open_url(url):
	web.open_new_tab(url)
	print 'run_to_use_default_browser_open_url open url ending ....'
	
#firefox浏览器	
def use_firefox_open_url(url):
	browser_path=r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe'
	#这里的‘firefox'只是一个浏览器的代号,可以命名为自己认识的名字,只要浏览器路径正确
	web.register('firefox', web.Mozilla('mozilla'), web.BackgroundBrowser(browser_path))
	#web.get('firefox').open(url,new=1,autoraise=True)
	web.get('firefox').open_new_tab(url)
	print 'use_firefox_open_url open url ending ....'
#谷歌浏览器
def use_chrome_open_url(url):
	browser_path=r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
	web.register('chrome', None,web.BackgroundBrowser(browser_path))
	web.get('chrome').open_new_tab(url)
	print 'use_chrome_open_url open url ending ....'
#Opera浏览器	
def use_opera_open_url(url):
	browser_path=r'C:\Program Files (x86)\Opera\launcher.exe'
	web.register('opera', None,web.BackgroundBrowser(browser_path))
	web.get('chrome').open_new_tab(url)
	print 'use_opera_open_url open url ending ....'
#千影浏览器
def use_qianying_open_url(url):
	browser_path=r'C:\Users\Administrator\AppData\Roaming\qianying\qianying.exe'
	web.register('qianying', None,web.BackgroundBrowser(browser_path))
	web.get('qianying').open_new_tab(url)
	print 'use_qianying_open_url open url ending ....'
#115浏览器	
def use_115_open_url(url):
	browser_path=r'C:\Users\Administrator\AppData\Local\115Chrome\Application\115chrome.exe'
	web.register('115', None,web.BackgroundBrowser(browser_path))
	web.get('115').open_new_tab(url)
	print 'use_115_open_url open url ending ....'
	
#IE浏览器	
def use_IE_open_url(url):
	browser_path=r'C:\Program Files (x86)\Internet Explorer\iexplore.exe'
	web.register('IE', None,web.BackgroundBrowser(browser_path))
	web.get('IE').open_new_tab(url)
	print 'use_IE_open_url open url ending ....'
	
#搜狗浏览器
def use_sougou_open_url(url):
	browser_path=r'D:\Program Files(x86)\SouExplorer\SogouExplorer\SogouExplorer.exe'
	web.register('sougou', None,web.BackgroundBrowser(browser_path))
	web.get('sougou').open_new_tab(url)
	print 'use_sougou_open_url open url ending ....'
	
#浏览器关闭任务	
def close_broswer():
	os.system('taskkill /f /IM SogouExplorer.exe') 
	print 'kill SogouExplorer.exe'
	os.system('taskkill /f /IM firefox.exe') 
	print 'kill firefox.exe'
	os.system('taskkill /f /IM Chrome.exe') 
	print 'kill Chrome.exe'
	os.system('taskkill /f /IM launcher.exe') 
	print 'kill launcher.exe'
	os.system('taskkill /f /IM qianying.exe') 
	print 'kill qianying.exe'
	os.system('taskkill /f /IM 115chrome.exe') 
	print 'kill 115chrome.exe'
	os.system('taskkill /f /IM iexplore.exe') 
	print 'kill iexplore.exe'
	
#测试运行主程序
def broswer_test():	
	url='https://www.baidu.com'	
	run_to_use_default_browser_open_url(url)
	use_firefox_open_url(url)
	#use_chrome_open_url(url)
	use_qianying_open_url(url)
	use_115_open_url(url)
	use_IE_open_url(url)
	use_sougou_open_url(url)
	time.sleep(20)#给浏览器打开网页一些反应时间
	close_broswer()
if __name__ == '__main__': 
	print ''''' 
   ***************************************** 
   ** Welcome to python of browser  ** 
   **  Created on 2017-05-07   ** 
   **  @author: Jimy _Fengqi   ** 
   ***************************************** 
	''' 
	broswer_test()	
	

好了,上面的程序是测试实例, 下面对这些内容做一个整合,简化一下代码,来实现本文的根本目的

#coding:utf-8
import time
import webbrowser as web
import os
import random
#随机选择一个浏览器打开网页
def open_url_use_random_browser():
	#定义要访问的地址
	url='https://www.baidu.com'
	#定义浏览器路径
	browser_paths=[r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe',
							r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe',
							r'C:\Program Files (x86)\Opera\launcher.exe',
							r'C:\Users\Administrator\AppData\Roaming\qianying\qianying.exe',
							r'C:\Users\Administrator\AppData\Local\115Chrome\Application\115chrome.exe',
							r'C:\Program Files (x86)\Internet Explorer\iexplore.exe',
							r'D:\Program Files(x86)\SouExplorer\SogouExplorer\SogouExplorer.exe'
							]
	#选择一个浏览器
	def chose_a_browser_open_url(browser_path,url):
		#如果传入的浏览器位置不存在,使用默认的浏览器打开
		if not browser_path:
			print 'using default browser to open url'
			web.open_new_tab(url)#使用默认浏览器,就不再结束进程
		else:
			#判断浏览器路径是否存在
			if not os.path.exists(browser_path):
				print 'current browser path not exists,using default browser'
				#浏览器位置不存在就使用默认的浏览器打开
				browser_path=''
				chose_a_browser_open_url(chose_a_browser_open_url,url)
			else:
				browser_task_name=browser_path.split('\\')[-1]#结束任务的名字
				browser_name=browser_task_name.split('.')[0]#自定义的浏览器代号
				print browser_name
				web.register(browser_name, None,web.BackgroundBrowser(browser_path))
				web.get(browser_name).open_new_tab(url)#使用新注册的浏览器打开网页
				print 'using %s browser open url successful' % browser_name
				time.sleep(5)#等待打开浏览器
				kill_cmd='taskkill /f /IM '+browser_task_name#拼接结束浏览器进程的命令
				os.system(kill_cmd) #终结浏览器
	browser_path=random.choice(browser_paths)#随机从浏览器中选择一个路径
	chose_a_browser_open_url(browser_path,url)
if __name__ == '__main__': 
	print ''''' 
   ***************************************** 
   ** Welcome to python of browser  ** 
   **  Created on 2017-05-07   ** 
   **  @author: Jimy _Fengqi   ** 
   ***************************************** 
	'''
	open_url_use_random_browser()	

PS:本程序在windows上面运行,python版本是2.7

相关推荐:

Python实现接受任意个数参数的函数

Python实现针对给定字符串寻找最长非重复子串

The above is the detailed content of Python implements randomly calling a browser to open a web page. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

What are unit tests in Python?What are unit tests in Python?Apr 30, 2025 pm 02:05 PM

The article discusses unit tests in Python, their benefits, and how to write them effectively. It highlights tools like unittest and pytest for testing.

What are Access Specifiers in Python?What are Access Specifiers in Python?Apr 30, 2025 pm 02:03 PM

Article discusses access specifiers in Python, which use naming conventions to indicate visibility of class members, rather than strict enforcement.

What is __init__() in Python and how does self play a role in it?What is __init__() in Python and how does self play a role in it?Apr 30, 2025 pm 02:02 PM

Article discusses Python's \_\_init\_\_() method and self's role in initializing object attributes. Other class methods and inheritance's impact on \_\_init\_\_() are also covered.

What is the difference between @classmethod, @staticmethod and instance methods in Python?What is the difference between @classmethod, @staticmethod and instance methods in Python?Apr 30, 2025 pm 02:01 PM

The article discusses the differences between @classmethod, @staticmethod, and instance methods in Python, detailing their properties, use cases, and benefits. It explains how to choose the right method type based on the required functionality and da

How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment