我正在编写一个python脚本,我右键单击一个文件,单击上下文菜单项。点击它会打开一个网页。我必须验证网页的网址。如何将控件从操作系统转移到浏览器并获取当前URL。
答案 0 :(得分:3)
为什么不调用requests.get(url)并检查响应代码。另一种选择是调用request.head(url)
>>> import requests
>>> url1 = 'http://example.com'
>>> url2 = 'http://sdsdsdsdsdss.com'
>>> r = requests.head(url1)
>>> r.status_code
200
>>> r = requests.head(url2, timeout=5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/requests/api.py", line 77, in head
return request('head', url, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 383, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 486, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 387, in send
raise Timeout(e)
requests.exceptions.Timeout: (<urllib3.connectionpool.HTTPConnectionPool object at 0x7f4e77635950>, 'Connection to sdsdsdsdsdss.com timed out. (connect timeout=5)')
>>>
您需要处理异常。有关请求模块的详细信息:http://docs.python-requests.org/en/latest/
如果您确实需要打开网络浏览器,可以使用此库:https://docs.python.org/2/library/webbrowser.html