[Python] how to get the dm text in instagram from selenium?

Discussão em 'Python' iniciado por Stack, Março 26, 2025.

  1. Stack

    Stack Membro Participativo

    I want to get the text of the sender on my console, I tried beautiful soup for scraping but it didn't work. I had used several other features like XPath and different class names on selenium but not able to resolve this issue.

    Here, is my code,

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.keys import Keys
    import time

    myemail = "<username>"
    mypassword = "<password>"
    friendusernames = ["<>sender username"]
    PATH = "C:/Chromedriver.exe"
    driver = webdriver.Chrome(PATH)
    url = "https://www.instagram.com/"
    driver.get(url)


    usernamebox = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.NAME, 'username')))
    usernamebox.send_keys(myemail)
    passwordbox = driver.find_element_by_name('password')
    passwordbox.send_keys(mypassword)
    loginbutton = driver.find_element_by_css_selector('.Igw0E')
    loginbutton.click()
    print("Logging in")

    dmbtn = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, '.xWeGp')))
    dmbtn.click()

    notificationsnotnow = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, '.HoLwm')))
    notificationsnotnow.click()


    for friendusername in friendusernames:
    searchuser = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, '.EQ1Mr')))
    searchuser.click()

    searchuserbox = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, '.j_2Hd')))
    searchuserbox.send_keys(friendusername)

    time.sleep(3)
    firstuser = driver.find_element_by_xpath(
    '/html/body/div[5]/div/div/div[2]/div[2]/div[1]/div')
    firstuser.click()


    pressingnext = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, '.rIacr')))
    pressingnext.click()


    names = driver.find_element_by_class_name(
    '_7UhW9 > span').text

    # names = driver.find_element_by_class_name(
    # '.xLCgt').text

    # names = driver.find_element_by_class_name(
    # '.MMzanKV-D4').text

    # names = driver.find_element_by_class_name(
    # '.p1tLr').text
    # names = driver.find_element_by_class_name(
    # '.hjZTB').text

    print(names)

    time.sleep(1)


    I want this text on my console


    [​IMG]

    How, can I do so??

    Continue reading...

Compartilhe esta Página