【问题标题】:How to solve this problem with request.get in python?如何在 python 中使用 request.get 解决这个问题?
【发布时间】:2021-09-21 01:32:30
【问题描述】:
import urllib.request
import urllib.parse
import re

import requests
def pesquisar(string):
    str = string.replace(" ", "+")
    print(str)
    searching = urllib.request.urlopen("https://www.youtube.com/results?search_query={}".format(str))
    search_result = requests.get(searching).text
    print(search_result)

我正在构建一个函数,它接收一个短语并搜索包含这个词的 youtube 视频,但我收到了这个错误:

requests.exceptions.MissingSchema:无效的 URL '':未提供架构。也许你的意思是 http://?

关于如何纠正这个问题的任何提示?

【问题讨论】:

  • 你为什么同时使用urllibrequests
  • urrlib.request 永远退休(或应该是 imo)。 requests 是它的继任者 :-)

标签: python python-3.x python-requests request


【解决方案1】:

requests.get 接受一个 URL。但是您将urllib.request.urlopen 的响应传递给它,它不是URL,而是http.client.HTTPResponse。查看http.client.HTTPResponse here 的可能方法。

其实,既然你已经用urllib.request.urlopen获取了URL,就不用再调用requests.get了。只选择一个。因此,最好通过requests

...
searching = requests.get("https://www.youtube.com/results?search_query={}".format(str))
search_result = searching.text
print(search_result)
...

或者如果你真的想使用urllib:

...
searching = urllib.request.urlopen("https://www.youtube.com/results?search_query={}".format(str))
search_result = searching.read()
print(search_result)
...

【讨论】:

  • 我投了反对票,因为我认为requests 的建议应该在urllib 之前
  • @rv.kvetch 你说得对,我换了他们并指出requests 更可取。
  • 我觉得不错 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-06
相关资源
最近更新 更多