Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: name 'requests' is not defined [closed]

I have taken this code as for help "Python getting all links from a google search result page" .

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.

I am trying to extract the related searched links from Google Search Result, but I don't know why I'm getting this error.

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
like image 792
user3440716 Avatar asked Nov 12 '14 19:11

user3440716


People also ask

How do you solve NameError name is not defined?

The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.

How do you overcome NameError in Python?

To specifically handle NameError in Python, you need to mention it in the except statement. In the following example code, if only the NameError is raised in the try block then an error message will be printed on the console.

Why am I getting a NameError in Python?

What Is a NameError in Python? In Python, the NameError occurs when you try to use a variable, function, or module that doesn't exist or wasn't used in a valid way. Some of the common mistakes that cause this error are: Using a variable or function name that is yet to be defined.

What does it mean when Python says not defined?

The Python "NameError: function is not defined" occurs when we try to call a function that is not declared or before it is declared. To solve the error, make sure you haven't misspelled the function's name and call it after it has been declared.


1 Answers

install 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=',''))
like image 152
Hasan Ramezani Avatar answered Oct 01 '22 03:10

Hasan Ramezani