如何处理quests.expections.InvalidURL:无法在python中解析?

How to Handle requests.exceptions.InvalidURL: Failed to parse in python?(如何处理quests.expections.InvalidURL:无法在python中解析?)

本文介绍了如何处理quests.expections.InvalidURL:无法在python中解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新用户。我不知道为什么,但请求总是引发InvalidURL异常:

>>> import requests
>>> r = requests.get('https://www.google.es/')

输出:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/requests/models.py", line 380, in prepare_url
    scheme, auth, host, port, path, query, fragment = parse_url(url)
  File "/usr/lib/python3/dist-packages/urllib3/util/url.py", line 392, in parse_url
    return six.raise_from(LocationParseError(source_url), None)
  File "<string>", line 3, in raise_from
urllib3.exceptions.LocationParseError: Failed to parse: https://www.google.es/

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/dist-packages/requests/api.py", line 76, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/requests/sessions.py", line 516, in request
    prep = self.prepare_request(req)
  File "/usr/local/lib/python3.7/dist-packages/requests/sessions.py", line 459, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/usr/local/lib/python3.7/dist-packages/requests/models.py", line 314, in prepare
    self.prepare_url(url, params)
  File "/usr/local/lib/python3.7/dist-packages/requests/models.py", line 382, in prepare_url
    raise InvalidURL(*e.args)
requests.exceptions.InvalidURL: Failed to parse: https://www.google.es/

此错误与我提供的URL无关。我如何处理此问题?

请求的版本为3.7.7和2.23.0。

致以最良好的祝愿。

推荐答案

由于urllib3的新版本(某些用户可能会遇到此问题),您遇到了错误。

错误不是由于requests,而是在安装requests 2.21.0+时安装的urllib3(新版本)出现问题。
若要避免这种情况,请尝试更新urllib3

python -m pip install --upgrade urllib3

或安装requests v2.21.0

pip uninstall requests # to remove current version
pip install requests==2.21.0
  • 只需将其降级到v2.21.0版本

这篇关于如何处理quests.expections.InvalidURL:无法在python中解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何处理quests.expections.InvalidURL:无法在python中解析?

基础教程推荐