Python NameError:未定义名称“请求”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26895371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NameError: name 'requests' is not defined
提问by user3440716
I have taken this code as for help "Python getting all links from a google search result page" .
我已将此代码作为帮助“ Python 从 google 搜索结果页面获取所有链接”。
When I try importing requests in Python 3.3.3, I get NameError: name 'requests' is not defined. I tested the "request" and "bs4" module using the CMD prompt and both show that this library has been installed.
当我尝试在 Python 3.3.3 中导入请求时,我得到NameError: name 'requests' is not defined. 我使用 CMD 提示符测试了“request”和“bs4”模块,两者都显示该库已安装。
I am trying to extract the related searched links from Google Search Result, but I don't know why I'm getting this error.
我正在尝试从 Google 搜索结果中提取相关的搜索链接,但我不知道为什么会出现此错误。
from bs4 import BeautifulSoup
page = requests.get("https://www.google.dz/search?q=see")
soup = BeautifulSoup(page.content)
import re
links = soup.findAll("a")
for link in soup.find_all("a",href=re.compile("(?<=/url\?q=)(htt.*://.*)")):
print (re.split(":(?=http)",link["href"].replace("/url?q=","")))
Error: Traceback (most recent call last):
File "C:/Users/DELL/Desktop/python/s/beauti.py", line 2, in <module>
page = requests.get("https://www.google.dz/search?q=see")
NameError: name 'requests' is not defined
采纳答案by Hasan Ramezani
install requests
安装 requests
pip install requests
and change your code like this:
并像这样更改您的代码:
from bs4 import BeautifulSoup
import requests
page = requests.get("https://www.google.dz/search?q=see")
soup = BeautifulSoup(page.content)
links = soup.findAll("a")
for link in links:
if link['href'].startswith('/url?q='):
print (link['href'].replace('/url?q=',''))

