搜尋
首頁後端開發Python教學python實作隨機呼叫一個瀏覽器開啟網頁

python實作隨機呼叫一個瀏覽器開啟網頁

Apr 21, 2018 pm 03:15 PM
firefoxpythonwebkit

下面为大家分享一篇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实现针对给定字符串寻找最长非重复子串

以上是python實作隨機呼叫一個瀏覽器開啟網頁的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表的內存足跡與python數組的內存足跡相比如何?列表的內存足跡與python數組的內存足跡相比如何?May 02, 2025 am 12:08 AM

列表sandnumpyArraysInpythonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,with withOverHeadeBheadaroundAroundaround64byty64-bitsysysysysysysysysyssyssyssyssysssyssys2)

部署可執行的Python腳本時,如何處理特定環境的配置?部署可執行的Python腳本時,如何處理特定環境的配置?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehavecorrectlyacrycrosdevelvermations,分期和生產,USETHESTERTATE:1)Environment varriablesForsimplesettings,2)configurationfilesfilesForcomPlexSetups,3)dynamiCofforComplexSetups,dynamiqualloadingForaptaptibality.eachmethodoffersuniquebeneiquebeneqeniquebenefitsandrefitsandrequiresandrequiresandrequiresca

您如何切成python陣列?您如何切成python陣列?May 01, 2025 am 12:18 AM

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

在什麼情況下,列表的表現比數組表現更好?在什麼情況下,列表的表現比數組表現更好?May 01, 2025 am 12:06 AM

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

如何將Python數組轉換為Python列表?如何將Python數組轉換為Python列表?May 01, 2025 am 12:05 AM

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器