gpt4 book ai didi

Python 无法从 urllib.request 中找到模块请求

转载 作者:太空宇宙 更新时间:2023-11-04 04:55:09 27 4
gpt4 key购买 nike

Python 无法从 urllib.request 中找到模块请求

更新: - 好吧,我尝试用 python3 运行它......请参阅:

martin@linux-3645:~/dev/python> Python3 w9.py
If 'Python3' is not a typo you can use command-not-found to lookup the package that contains it, like this:
cnf Python3
martin@linux-3645:~/dev/python>

当尝试在 Python 代码中从 urllib.request 导入 Request 时,无法找到包。

>>> from urllib.request import urlopen as uReq
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named request

查看我正在尝试运行的代码...:

import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = "https://wordpress.org/plugins/participants-database/"
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")

ttt = page_soup.find("div", {"class":"plugin-meta"})
text_nodes = [node.text.strip() for node in ttt.ul.findChildren('li')[:-1:2]]

不幸的是,这会导致:

martin@linux-3645:~/dev/python> python w9.py
Traceback (most recent call last):
File "w9.py", line 3, in <module>
from urllib.request import urlopen as uReq
ImportError: No module named request
martin@linux-3645:~/dev/python>

嗯:Python 2 中没有 urllib.request 模块,该模块仅存在于 Python 3 中。

我做了一些搜索并找到了一个可能的解决方案:请参阅此soultion:我可以使用 urllib2 代替:

from urllib2 import Request

从模块文档的顶部:注意: urllib2 模块在 Python 3 中被拆分为多个模块,名为 urllib.request 和 urllib.error。将源代码转换为 Python 3 时,2to3 工具将自动调整导入。

但是等等:我以为我已经可以运行 Python 3 并且我会继续使用该版本;我尝试执行的代码显然是为 Python 3 设计的。

这里出了什么问题?

最佳答案

您的示例代码适用于 python3。请注意,您必须以小写形式运行“python3”,而不是Python3。

使用您发布的示例代码,您不会在屏幕上看到任何输出,因为您没有要求任何输出。

如果在末尾添加 print(text_nodes),您将得到以下输出:

['Version: 1.7.7.7', 'Active installations: 10,000+', 'Tested up to: 4.9.4']

关于Python 无法从 urllib.request 中找到模块请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48932103/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com