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
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.
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.
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.
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.
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=',''))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With