I'm struggling with a Python Bot issue, as it seems the driver is not being acknowledged

I'm encountering an error with my code while trying to run a WhatsApp bot. Can anyone help me figure out why this error is occurring? Here is the error message that I am getting:

Error:

Traceback (most recent call last):
  File "C:\Users\lwyzb\OneDrive\Documentos\Bot whatsapp\wppBot.py", line 32, in <module>
    bot.MsgSend()
  File "C:\Users\lwyzb\OneDrive\Documentos\Bot whatsapp\wppBot.py", line 16, in MsgSend
    self.driver.get('https://web.whatsapp.com/')
AttributeError: 'WhatsappBot' object has no attribute 'driver'

Code:

from selenium import webdriver
import time

class WhatsappBot:
    def _init_(self):
        self.msg = "Bom dia famiiiilia"
        self.groups = ["Churras ??/?? 🍖🔥🤗", "PARÇAS (Nova formação)", "Parças incorporated"]
        options = webdriver.ChromeOptions()
        options.add_argument('lang=pt-br')
        self.driver = webdriver.Chrome(executable_path=r'./chromedriver.exe')

    def MsgSend(self):
          # <span dir="auto" title="PARÇAS (Nova formação)" class="_3ko75 _5h6Y_ _3Whw5">PARÇAS (Nova formação)</span>
          # <div tabindex="-1" class="_3uMse">
          # <span data-testid="send" data-icon="send" class="">
          self.driver.get('https://web.whatsapp.com/')
          time.sleep(30)
          for group in self.groups:
              group = self.driver.find_element_by_xpath(f"//span[@title='{group}']")
              time.sleep(3)
              group.click()
              chatBox = self.driver.find_element_by_class_name('_3uMse')
              time.sleep(3)
              chatBox.click()
              chatBox.send_keys(self.msg)
              send = self.driver.find_element_by_xpath("//span[@data-icon='send']")
              time.sleep(3)
              send.click()
              time.sleep(5)

bot = WhatsappBot()
bot.MsgSend()         

Answer â„–1

Your init method is named incorrectly - it should be __init__, not _init_:

from selenium import webdriver
import time

class WhatsappBot:
    def __init__(self):
        self.msg = "Good morning family"
        self.groups = ["BBQ ??/?? 🍖🔥🤗", "BROS (New lineup)", "Brothers incorporated"]
        options = webdriver.ChromeOptions()
        options.add_argument('lang=pt-br')
        self.driver = webdriver.Chrome(executable_path=r'./chromedriver.exe')

    def SendMessage(self):
          # <span dir="auto" title="BROS (New lineup)" class="_3ko75 _5h6Y_ _3Whw5">BROS (New lineup)</span>
          # <div tabindex="-1" class="_3uMse">
          # <span data-testid="send" data-icon="send" class="">
          self.driver.get('https://web.whatsapp.com/')
          time.sleep(30)
          for group in self.groups:
              group = self.driver.find_element_by_xpath(f"//span[@title='{group}']")
              time.sleep(3)
              group.click()
              chatBox = self.driver.find_element_by_class_name('_3uMse')
              time.sleep(3)
              chatBox.click()
              chatBox.send_keys(self.msg)
              send = self.driver.find_element_by_xpath("//span[@data-icon='send']")
              time.sleep(3)
              send.click()
              time.sleep(5)

bot = WhatsappBot()
bot.SendMessage()       

Python only recognizes the __init__ method - due to the missing underscores, Python did not interpret this as the initializer function and therefore did not execute it.

Answer â„–2

Everything is fine, except for the fact that two underscores are missing in __init__, which means the class is not properly initialized:

from selenium import webdriver
import time

class WhatsappBot:
    def __init__(self):
        self.msg = "Good morning famiiiily"
        self.groups = ["BBQ ??/?? 🍖🔥🤗", "SQUAD (New formation)", "Squad incorporated"]
        options = webdriver.ChromeOptions()
        options.add_argument('lang=pt-br')
        self.driver = webdriver.Chrome(executable_path=r'./chromedriver.exe')

    def MsgSend(self):
          # <span dir="auto" title="SQUAD (New formation)" class="_3ko75 _5h6Y_ _3Whw5">SQUAD (New formation)</span>
          # <div tabindex="-1" class="_3uMse">
          # <span data-testid="send" data-icon="send" class="">
          self.driver.get('https://web.whatsapp.com/')
          time.sleep(30)
          for group in self.groups:
              group = self.driver.find_element_by_xpath(f"//span[@title='{group}']")
              time.sleep(3)
              group.click()
              chatBox = self.driver.find_element_by_class_name('_3uMse')
              time.sleep(3)
              chatBox.click()
              chatBox.send_keys(self.msg)
              send = self.driver.find_element_by_xpath("//span[@data-icon='send']")
              time.sleep(3)
              send.click()
              time.sleep(5)

bot = WhatsappBot()
bot.MsgSend()         

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to assign a default value of an object variable in an object method - Python

Using Windows 10, x64, and Python 2.7.8. I'm trying to implement the code below: class TrabGraph: def __init__(self): self.radius = 1.0 def circle(self, rad=self.radius): print(rad) test = TrabGraph() test.circ ...

Python code to verify if a specific condition is satisfied within a certain time period

Seeking to determine if certain conditions are met over a period of time. The data is structured as follows: Datetime Valve1 Valve2 01/01/2020 11:00:01 1 0 The condition being evaluated is: (Valve1=1 for 1h) and (Valve-0 for 1h) Utilizing rolling ...

There are no interactive features shown in the screenshot

I'm capturing a screenshot using the following code: from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities dcap = dict(DesiredCapabilities.PHANTOMJS) dcap["phantomjs.page.settings.userAgent"] = ...

Merge a series of rows into a single row when the indexes are consecutive

It seems like I need to merge multiple rows into a single row in the animal column. However, this should only happen if they are in sequential order and contain lowercase alphabet characters. Once that condition is met, the index should restart to maintain ...

Using Python and BeautifulSoup to Extract CME Data

Seeking assistance in extracting a specific list of symbols along with their corresponding prices from the CME website. I have successfully gathered a list of symbols, but am struggling to retrieve the prices displayed in each row. Encountering difficulti ...

Utilizing Python Logging within a Docker Environment

Currently, I am experimenting with running a Python script within a Docker container on an Ubuntu web server. My goal is to locate the log file that is being created by the Python Logger Module. The Python script I am using can be found below: import time ...

Guide on scraping at regular intervals using Python Selenium Chrome Driver

Scenario: I am facing a challenge with a website that requires me to scrape information from it at regular intervals. The site involves user input, so I opted to use Selenium for this task. The workflow is such that the user can interact with the web brows ...

Error: Unable to access the 'uname' attribute in the 'os' module within the dockerized environment (docker with Django REST framework)

Hello, I am working with Docker and DRF, and facing some challenges. Initially, I executed this command: pip install -r requirements.txt --use-deprecated=legacy-resolver Below are the contents of my requirements file: asgiref==3.5.2 backports.zoneinfo==0 ...

Error encountered: Failure to construct URL for endpoint 'Bookdetails'. Have you overlooked supplying values for the parameter 'book_id'?

I have been troubleshooting this issue and reviewed similar threads, yet despite verifying all options, the problem persists. My code includes: application.py @app.route("/Booksearch/<int:book_id>", methods=["GET", "POST"]) def Bookdetails(book_id ...

Tips for narrowing down a sqlalchemy query based on a specific field within the most recent child entry

My current database structure consists of two tables that are roughly described in SQLAlchemy mapping as follows: class Parent(Base): __tablename__ = "parent" parent_id = Column(Integer, primary_key=True) class Child(Base): __tablename__ = " ...

When using Selenium webdriver, the function find_elements_by_X sometimes results in an empty list being

My objective is to compile a list of the names of all newly posted items on within a 24-hour period. After some research, I've discovered that Selenium is the ideal tool for this task as the website I am scraping is dynamic and loads more content as ...

When using Pandas to write to Excel, you may encounter the error message "Error: 'Workbook' object does not have the attribute 'add_worksheet'." This issue can cause the Excel file to become corrupted

I have been attempting to add a new sheet to an existing excel file while preserving the current content within it. Despite trying various methods, I keep encountering the same error message. Whenever I attempt to write to or save the file, I receive an At ...

Deciphering the inner workings of pyTorch code

Currently, I am struggling to grasp a specific section of the code within the ResNet architecture. You can find the complete code on this link: https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/02-intermediate/deep_residual_network/main-gpu. ...

Utilizing Python to extract data from a JSON file

I have been working on reading a JSON file in Python and have run into an issue where some top values are being skipped. I am currently debugging to identify the root cause of this problem. Here is the code snippet: data = json.load(open('pre.txt&apo ...

There was a TypeError encountered while trying to access the /datatable page. The datatable() function is missing a required positional argument, specifically the

In views.py def getDataTable(request, filename): csvFile = open(f'csv_upload_files/{filename}.csv', 'r') reader = csv.DictReader(csvFile) headers = [col for col in reader.fieldnames] data = [row for row in reader] re ...

Error thrown due to obtaining multiple objects using the `get_or_create` method

Here is a concise snippet of code I have for retrieving or creating a conversation for the current user: c, created = Conversation.objects.get_or_create( message__sender=request.user, content_type=get_content_type(request.POST['ct']), ...

Exploring the versatility of Selenium across complex multi-step iframes, focusing on the specific

I am currently exploring the process of testing PayPal payment using selenium/selenide. As part of this, I need to wait for the embedded frame to load, switch to it, input login details, and click the login button. However, my challenge lies in waiting f ...

Using DataProvider to read an Excel file and skipping the first row

Unique Heading how can I skip the first row in a loop and avoid getting null values I'm trying to skip the first row by starting my loop at i=1, but it's returning null values for the first row. Problem with First Row Values how can I skip ...

Utilize Python to merge various XML files into a single Excel workbook, each file imported into a separate worksheet

I am looking to combine 20 XML files into a single Excel file, with each XML file as an individual worksheet. Although the structure of the XML files is consistent, the values vary. You can see how the XML file appears here. Only the X and Y values are ...

Approaches for transforming data and displaying the output in HTML using Django

My data is structured as follows: ws=[{'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 4>}, {'a': datetime.date(2020, 8, 31), 'b': <BB: 01>, 'c': <CC: 5>}, ...