AttributeError: module 'bs4' has no attribute 'BeautifulSoup' - python-3.x

Traceback (most recent call last):
File "bs4.py", line 1, in <module>
import bs4
File "/home/mhadi/Desktop/bs4test/bs4.py", line 5, in <module>
soup = bs4.BeautifulSoup(site,'lxml')
AttributeError: module 'bs4' has no attribute 'BeautifulSoup'
The code:
import bs4
import urllib.request
site = urllib.request.urlopen('http://127.0.0.1:8000').read()
soup = bs4.BeautifulSoup(site,'lxml')
#for i in site:
# print(site[i])
print(soup)

The problem is that your filename is bs4.py. Now if you write an import statement, Python will first look for local files with that name. So it assumes that your import bs4 refers to your own file. Your file will thus aim to import itself, but it obviously does not contain the desired module.
A quick fix is renaming the file. For instance into bs4tests.py. Then you can use import bs4.
Alternatively, you can for instance try to remove the local path, like:
import sys # import sys package
old_path = sys.path[:] # make a copy of the old paths
sys.path.pop(0) # remove the first one (usually the local)
import bs4 # import the package
sys.path = old_path # restore the import path

Related

ImportError: cannot import name 'HTMLSession' from 'requests_html'

When I tried to use the new module requests_html using the example of its website,I found the console displays information in the title.
I have successfully installed requests_html using pip install requests_html
I have updated the python to python3.7 (64-bit)
The messages of console:
Traceback (most recent call last):
File "C:/Users/owlish/PycharmProjects/python34/requests.py", line 2, in <module>
from requests_html import HTMLSession
File "C:\Users\owlish\AppData\Local\Programs\Python\Python37\lib\site-packages\requests_html.py", line 10, in <module>
import requests
File "C:\Users\owlish\PycharmProjects\python34\requests.py", line 2, in <module>
from requests_html import HTMLSession
ImportError: cannot import name 'HTMLSession' from 'requests_html' (C:\Users\owlish\AppData\Local\Programs\Python\Python37\lib\site-packages\requests_html.py)
code:
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://python.org/')
I expect it to work without an error,like the examples https://html.python-requests.org/.
With AhmedHawary's help,I found the reason for the error:I had a file named requests.py , which confilcted with the keywords . It worked fine after I renamed the file name.

Pyinstaller modulenotfound error: no module name 'mysql'

I created an executable using pyinstaller. My scripts all run fine but when i run the executable i get the error below. It appears it doesnt like the mysql connector in DBconnection.py. Any help is appreciated.
Traceback (most recent call last):
File "main.py", line 8, in
File "c:\programdata\anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_i
mporters.py", line 631, in exec_module
File "DBconnection.py", line 2, in
ModuleNotFoundError: No module named 'mysql'
[4780] Failed to execute script main
DBconnection.py:
from configparser import ConfigParser
from mysql.connector import MySQLConnection
import Global
def create_db_connection(filename= 'my.ini', section= 'dbconnection'):
parser = ConfigParser()
parser.read(filename)
db = {}
if parser.has_section(section):
items = parser.items(section)
for item in items:
db[item[0]] = item[1]
else:
raise Exception('{0} not found in the {1} file'.format(section. filename))
#global conn
Global.conn = MySQLConnection(**db)
print(Global.conn)
def close_db_connection():
Global.conn.close()
main.py:
from servers import updateservers
from policies import updatepolicies
from updateguardpoints import updateguardpoints
from activities import updateactivities
from guardpointstatus import updateguardpointstatus
from application import updateapplication
from application_servers import updateapplication_servers
from DBconnection import create_db_connection
from DBconnection import close_db_connection
from TrouxConnection import TrouxConnection
from TrouxConnection import CloseTrouxConnection
import Global
create_db_connection()
TrouxConnection()
updateservers()
updatepolicies()
updateguardpoints()
updateactivities()
updateguardpointstatus()
updateapplication()
updateapplication_servers()
CloseTrouxConnection()
close_db_connection()
reinstalled mysql - connector using PIP. Issue resolved

ImportError: No module named url

when i run the the given code in prepare_dataset.py whose code is below as
from urllib.request
import urlopen
import json as simplejson
def main():
# Download and prepare datasets
list_generator = video_list_generator.Generator("playlists.json", youtube_api_client.Client("AIzaSyD_UC-FpXbJeWzPfscLz9RhqSjKwj33q6A"))
video_list = list_generator.get_video_list("piano")
downloader = youtube_video_downloader.Downloader()
downloader.download_from_list(video_list)
if __name__ == '__main__':
main()
as python prepare_dataset.py in command-line then i get these errors
Traceback (most recent call last):
File "prepare_dataset.py", line 1, in <module>
from urllib.request import urlopen
ImportError: No module named request
How can i get to run the above file any idea guys?

Python version related error

I am trying to generate an HTML test report by using Selenium webdriver library HTMLTestRunner. I am using Python 3.4 version and I have a version related error. Refer following snippet.
import unittest`enter code here`
import HTMLTestRunner
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.keys import Keys
class GreenlamTest(unittest.TestCase):
#classmethod
def setUp(cls):
cls.driver=webdriver.Firefox()
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
cls.driver.get('https://www.google.co.in')
def test_checkTitle(self):
assert "Google" in self.driver.title
def test_searchtest(self):
driver = self.driver
elem = self.driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
#classmethod
def tearDown(cls):
cls.driver.quit()
if __name__ == '__main__':
HTMLTestRunner.main
Output
Finding files... done.
Traceback (most recent call last):
File "C:\Users\vaibhav\Desktop\Selenium Softwares\eclipse-jee-luna-SR2-win32-x86_64\eclipse\plugins\org.python.pydev_4.0.0.201504132356\pysrc\pydev_runfiles.py", line 468, in __get_module_from_str
mod = __import__(modname)
File "C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\Htmlreport.py", line 2, in <module>
import HTMLTestRunner
File "C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\HTMLTestRunner.py", line 94, in <module>
import StringIO
ImportError: No module named 'StringIO'
ERROR: Module: Htmlreport could not be imported (file: C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\Htmlreport.py).
Importing test modules ... done.
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
You are getting error because your folder name Selenium Softwares has a space in it where your Htmlreport is present. Replace the folder name to exclude space out of it, probably an underscore or camelCase, etc... like this Selenium_Softwares . Here's how -
file: C:\Users\vaibhav\Desktop\Selenium_Softwares\Practice\pythondemo\Htmlreport.py)
Hope this helps.

python 3 import not working

I am new to Python 3 and am rewriting a Python 2 program. I have the following file system:
|-00_programs / test.py
|-01_classes / class_scrapper.py
I want to import the class scrapper from the file class_scrapper:
Here is class_scrapper.py:
# -*- coding: utf-8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
class scrapper:
def get_html(self, url):
html = False
headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }
try:
html = urlopen(url, '', headers).read()
except Exception as e:
print ("Error getting html :" + str(e))
return html
Here is test.py:
# -*- coding: utf-8 -*-
import sys
sys.path.insert(0, "./../01_classes/class_scrapper.py")
from class_scrapper import scrapper
o_scrapper = scrapper()
While executing I got:
Traceback (most recent call last):
File "/src/00_programs/tets.py", line 6, in <module>
from class_scrapper import scrapper
ImportError: No module named 'class_scrapper'
What should be changed on the import command to make that work?
Thanks,
Romain.
If the interpreter is saying module doesn't exist, it means you must have spelt it wrong when importing, or the module is either not in your program's directory or the python directory which has all of the other main modules.

Resources