【问题标题】:Trying to run the requests module still won't work despite installing it (via pip3)?尽管安装了它(通过pip3),但尝试运行请求模块仍然无法工作?
【发布时间】:2017-10-15 02:29:00
【问题描述】:

想要保持简短而甜蜜。

我正在尝试运行 requests 模块,并在 Python 3.6.3 上使用 urllib。我在 MacOSX 10.12 上。

我安装了 Pip3 并运行了 pip3 命令,例如“pip3 install requests”,应该会激活请求,对吧...?

Here's my screen when I type "pip3 freeze" if it helps.

谢谢!

【问题讨论】:

  • 向我们展示您尝试使用请求时遇到的错误。
  • 绿色代表我执行命令的特定文件夹,橙色是网站链接的特定部分。这是一个测试,我试图使用 requests 模块从网站中提取特定的图像链接。它在过去有效,当我为要搜索的代码键入一个数字值(查看 jpg 子域是否存在)时,它会非常快速地循环遍历它们而没有错误(使用 pip)。但是一周前我不小心删除了一些东西,现在它运行了,但给出了超时错误。不知道该怎么做。
  • 最后一件事,实际代码示例,在 download.py 中:imgur.com/a/2i8qN

标签: python macos python-3.x pip python-requests


【解决方案1】:

当您执行import urllib.request 时,您实际上并没有导入您安装的requests 包,而只是使用了内置urllib 包的request 模块。你应该改用import requests。你可以找到requests 包文档here。这是一些下载文件的示例代码

import requests
url = 'http://example.com/image.png'
r = requests.get(url)
with open("image.png", "wb") as image:
    image.write(r.content)

您的输出还显示Operation timed out 为错误,这通常是与网络相关的问题。


既然你问了,这就是使用请求编写代码示例的方法:

import requests

start = int(input("Start range: "))
stop = int(input("End range: "))

for i in range(start, stop+1):
    filename = str(i).rjust(6, '0')+".jpg"
    url = 'https://website.com/Image_' + filename
    print(url)
    r = requests.get(url)
    with open(filename, "wb") as image:
        image.write(r.content)

【讨论】:

  • 我会用什么代替这些行:try: urllib.request.urlretrieve(url, filename) except urllib.error.URLError as e: if I'm using "import requests"?
  • 看来您的编程之旅才刚刚开始。我正在添加您要求的代码。但是,我强烈建议您花时间了解 Python 语言和一般编程的基础知识。更改非常简单,您应该比它的作用更了解它的工作原理。
猜你喜欢
  • 1970-01-01
  • 2019-10-09
  • 1970-01-01
  • 2018-11-30
  • 2021-01-21
  • 2021-03-30
  • 2018-11-01
  • 1970-01-01
  • 2019-06-05
相关资源
最近更新 更多