Python Selenium在使用无效URL方案时不会引发异常
我已经编写了两个脚本:一个使用Python Selenium在使用无效URL方案时不会引发异常,python,python-3.x,selenium,selenium-webdriver,web-scraping,Python,Python 3.x,Selenium,Selenium Webdriver,Web Scraping,我已经编写了两个脚本:一个使用请求,另一个使用selenium 当我执行第一个脚本时,我看到它从未打印任何内容,因为当出现错误时,它无法通过这一行res=requests.get(link),因此打印从未发生。然而,在硒的情况下,我得到了不同的行为。我知道我提供了一个无效链接,但我仍然可以看到这行打印的结果(“正在执行:“+driver.current\u url)产生了什么 当selenium脚本点击这一行时,我如何停止它呢?driver.get(link) 第一个脚本(其行为方式正确): 第
请求
,另一个使用selenium
当我执行第一个脚本时,我看到它从未打印任何内容,因为当出现错误时,它无法通过这一行res=requests.get(link)
,因此打印从未发生。然而,在硒的情况下,我得到了不同的行为。我知道我提供了一个无效链接,但我仍然可以看到这行打印的结果(“正在执行:“+driver.current\u url)
产生了什么
当selenium脚本点击这一行时,我如何停止它呢?driver.get(link)
第一个脚本(其行为方式正确):
第二个脚本(在抛出错误时运行平稳):
InvalidSchema
是特定于请求的异常请求
仅支持HTTP
和HTTPS
协议,并且get\u适配器
方法检查URL架构是否在['HTTP',HTTPS']
列表中。如果未InvalidSchema
引发异常
Selenium没有这种无效的模式处理程序,因此(正如预期的那样)在您希望使用类似于“httppss”的模式获取URL时不会引发异常
当然,您可以在本地更新selenium.common.exceptions
模块,因此它将包含
class InvalidSchemaException(WebDriverException):
"""Raises if URL-schema is not supported"""
pass
将导入添加到webdriver
模块:
from selenium.common.exceptions import (InvalidArgumentException,
WebDriverException, InvalidSchemaException)
from urllib.parse import urlparse
并将get
修改为
def get(self, url):
"""
Loads a web page in the current browser session.
"""
schema = urlparse(url).scheme
if scheme.upper() not in ['HTTP', 'HTTPS']:
raise InvalidSchemaException('Schema "%s" is not supported' % scheme)
self.execute(Command.GET, {'url': url})
但这只是一种解决方法,只有当您真正需要它时,才可以使用这种方法请求
仅支持HTTP
和HTTPS
协议,并且get\u适配器
方法检查URL架构是否在['HTTP',HTTPS']
列表中。如果未InvalidSchema
引发异常
Selenium没有这种无效的模式处理程序,因此(正如预期的那样)在您希望使用类似于“httppss”的模式获取URL时不会引发异常
当然,您可以在本地更新selenium.common.exceptions
模块,因此它将包含
class InvalidSchemaException(WebDriverException):
"""Raises if URL-schema is not supported"""
pass
将导入添加到webdriver
模块:
from selenium.common.exceptions import (InvalidArgumentException,
WebDriverException, InvalidSchemaException)
from urllib.parse import urlparse
并将get
修改为
def get(self, url):
"""
Loads a web page in the current browser session.
"""
schema = urlparse(url).scheme
if scheme.upper() not in ['HTTP', 'HTTPS']:
raise InvalidSchemaException('Schema "%s" is not supported' % scheme)
self.execute(Command.GET, {'url': url})
但这只是一种解决方法,只有当您真正需要它时,才可以使用这种方法。您希望出现什么异常?为什么会抛出错误?当您试图访问无效的URL时,您的浏览器不会崩溃。Selenium发送了URL,浏览器成功地对此进行了投诉。您希望出现什么异常?为什么会抛出错误?当你试图访问一个无效的URL时,你的浏览器不会崩溃。