【问题标题】:Selenium throw no exception in case invalid URL-scheme used如果使用了无效的 URL 方案,Selenium 不会抛出异常
【发布时间】:2018-12-31 09:04:13
【问题描述】:

我编写了两个脚本:一个使用requests,另一个使用selenium

当我执行我的第一个脚本时,我发现它永远不会打印任何东西,因为当出现错误时它无法越过这一行res = requests.get(link),因此打印永远不会发生。但是,在硒的情况下,我会得到不同的行为。我知道我提供了一个无效链接,但我仍然可以看到 print("Executing: " + driver.current_url) 这一行产生的结果?

当我的 selenium 脚本到达 driver.get(link) 这一行时,我如何才能停止它,无论是否提供了无效的 url、没有有效的响应或根本没有 url?

第一个脚本(它以正确的方式运行):

import requests

link = "httppss://www.google.com/search?q=selenium"

res = requests.get(link) #error thrown here just as expected
print("Executing: " + res.url)

第二个脚本(抛出错误时运行平稳):

from selenium import webdriver

link = "httppss://www.google.com/search?q=selenium"

driver = webdriver.Chrome()
driver.get(link) #expected any error to be thrown here
print("Executing: " + driver.current_url)
driver.quit()

【问题讨论】:

  • Selenium 发送了 URL 并且浏览器成功地抱怨了它。你期待什么例外?
  • 为什么抛出错误?当您尝试访问无效的 URL 时,您的浏览器不仅会崩溃。

标签: python python-3.x selenium selenium-webdriver web-scraping


【解决方案1】:

InvalidSchemarequests 特定的异常。 requests 仅支持 HTTPHTTPS 协议,get_adapter 方法检查 URL-schema 是否在 ['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})

但这只是一种解决方法,只有在您确实需要它

时才可以使用此方法

【讨论】:

    猜你喜欢
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 2011-09-04
    • 2021-02-08
    • 2014-01-25
    • 1970-01-01
    相关资源
    最近更新 更多