2017-06-07 35 views
0

您能否建議如何處理每封未讀郵件的打開過程?Python打開每個未讀郵件

現在,它的工作原理是這樣的:

  1. 登錄到Gmail
  2. 打開收件箱
  3. 單擊未讀郵件
  4. 返回收件箱
  5. 打開一個未讀郵件

但我注意到硒不打開每封郵件。硒通過一封郵件打開。我試圖使用索引 - = 1,但它不起作用。

有代碼:

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']") 
+1

請檢查xpath返回多少個元素// * [@ class ='zF']。它可能只有一個。另外,Gmail具有動態類名稱。所以你不能用它來查找未讀郵件。 – Murthi

+0

謝謝。我檢查了它看起來不錯的元素數。看起來這不是動態類名。硒通過所有元素,但它不通過每封郵件。它每次跳過一封郵件。 – Jack

+1

你有沒有理由不使用gmail API?這會更直接。 – JeffC

回答

1

使用硒或報廢來解決這個問題是因爲某些原因的最佳選擇。

  1. 谷歌有動態加載的HTML,它可能會導致你很多問題。
  2. 你可能會遇到reCaptcha服務(我不是機器人)那麼是什麼?
  3. 這個非法操作通過谷歌規則,你可能會被阻止。

因此,我真的建議您使用Google API解決此問題。