Jack
Jack

Reputation: 121

Python opening each the unread emails

Could you please suggest how to handle the opening process of each unread mail ?

Now it works this way:

  1. Login to Gmail
  2. Open inbox
  3. Click on the unread mail
  4. Back to inbox
  5. Open next unread mail

But I noted that the selenium open not each mail. The selenium opens through one mail. I tried to use index -= 1 but it doesn't work.

There is code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.color import Color

driver = webdriver.Chrome(executable_path=r'/chromedriver_win32/chromedriver.exe')

driver.implicitly_wait(10)
driver.get('https://gmail.com')
assert 'Gmail' in driver.title

try:
    login = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@id='identifierId']")))
finally:
    driver.find_element_by_xpath("//*[@id='identifierId']").send_keys("********@gmail.com" + Keys.RETURN)
try:
    password = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, "//*[@id='password']/div[1]/div/div[1]/input")))
finally:
    driver.find_element_by_xpath("//*[@id='password']/div[1]/div/div[1]/input").send_keys(
    "PASSWORD" + Keys.RETURN)

wait = WebDriverWait(driver, 30)
unread_mails = driver.find_elements_by_xpath("//*[@class='zF']")
for index, mails in enumerate(unread_mails):
    print(unread_mails[index])
    if unread_mails[index].is_displayed():
        wait.until_not(EC.staleness_of(unread_mails[index]))
        try:
           unread_mails[index].click()
           index -= 2
        except StaleElementReferenceException:
           pass
     driver.get('https://mail.google.com')
     try:
        WebDriverWait(driver, 5).until(EC.alert_is_present(),
                                   'Timed out waiting for PA creation ' +
                                   'confirmation popup to appear.')
        confirmation_alert = driver.switch_to.alert
        confirmation_alert.accept()
     except TimeoutException:
        print('no alerts')
unread_mails = driver.find_elements_by_xpath("//*[@class='zF']")

Upvotes: 0

Views: 1169

Answers (1)

nivhanin
nivhanin

Reputation: 1918

Using selenium or scrapping to solve this issue is not the best choice for some reasons.

  1. Google have dynamic load of the HTML and it can cause you a lot of problems.
  2. You may come across with the reCaptcha service (Im not robot) then what?
  3. This illegal operation by google rules and you may be blocked.

Therefore I'm truly recommend you to use Google API to solve this issue.

Upvotes: 1

Related Questions