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中。
我做了一些搜索,发现了一个可能的解决办法:看到这个灵魂:我可以使用urllib2代替:
from urllib2 import Request
从模块文档的顶部: 注意:urllib2模块已经拆分为Python 3中名为urllib.request和urllib.error的几个模块。将源代码转换为Python 3时,2to3工具将自动调整导入。
但是等等:我认为我已经运行了Python 3并继续使用该版本;我试图执行的代码显然是为Python 3设计的。
这里出了什么问题?
答案 0 :(得分:1)
您的示例代码适用于python3。请注意,您必须运行&#34; python3&#34;小写,而不是Python3。
使用您发布的示例代码,您不会在屏幕上获得任何输出,因为您没有要求任何输出。
如果您在结尾添加print(text_nodes)
,您将获得以下输出:
[&#39;版本:1.7.7.7&#39;,&#39;有效安装:10,000 +&#39;,&#39;经测试: 4.9.4&#39;]