簡體   English   中英

Python-For Loop if語句跳至Selenium中的下一個迭代

[英]Python - For Loop if statement skip to next iteration in Selenium

我正在使用硒來遍歷變量參數的不同組合,並從網站下載數據。 但是,當沒有數據時,for循環功能將停止工作。 我還注意到,硒停止運行時,網頁上會包含一個標記為“無法產生結果”的文本。 因此,我想使用帶有硒的if語句來搜索“無法產生結果”,如果找到了上述文本,則跳到下一個循環。 一個例子是這樣的:

import os
from selenium import webdriver
import zipfile
import pandas as pd
import time

for i in to_loop:
    # directories
    link = 'http://www.gaez.iiasa.ac.at/w/ctrl?
_flow=Vwr&_view=Welcome&idAS=0&idFS=0&fieldmain=main_&idPS=0'

    ## Access Chrome Driver to use selenium
    # Define Download Directory
    chrome_options = webdriver.ChromeOptions()
    prefs = {'download.default_directory': 'C:/.../Download'}
    chrome_options.add_experimental_option('prefs', prefs)
    driver = webdriver.Chrome(
        executable_path='C:/.../chromedriver.exe',
        chrome_options=chrome_options)
    driver.get(link)

    # Enter username and password
    driver.find_element_by_name('_username').send_keys(username)
    driver.find_element_by_name('_password').send_keys(password)
    driver.find_element_by_id('buttonSubmit__login').click()

    # Click on Suitability and Potential Yield link
    driver.find_element_by_name('_targetfieldmain=main_py&_...').click()

    # Click on Agro-ecological suitability and productivity link
    driver.find_element_by_name('&fieldmain=main_py&idPS=0&...').click()
    # Click on Agro-ecological suitability and productivity list
    driver.find_element_by_css_selector('input[value="
{}"]'.format(i[0])).click()
    # Click on crop link
    driver.find_element_by_css_selector("input.linksubmit[value=\"▸ 
Crop\"]").click()
    AES_and_P = i[0]

    driver.find_element_by_css_selector('input[value="
{}"]'.format(i[1])).click()
    # Click on Water Supply Link
    driver.find_element_by_css_selector("input.linksubmit[value=\"▸ Water 
Supply\"]").click()
    Crop = i[1]

    driver.find_element_by_css_selector('input[value="
{}"]'.format(i[2])).click()
    # Click on Input Level Link
    driver.find_element_by_css_selector("input.linksubmit[value=\"▸ Input 
Level\"]").click()
    Water_Supply = i[2]

    driver.find_element_by_css_selector('input[value="
{}"]'.format(i[3])).click()
    Input_Level = i[3]

    # If statement to skip to next loop if text found
    data_check = driver.find_elements_by_partial_link_text('Cannot produce 
results.')
    if data_check[0].is_displayed():
        continue

    # Click on Time Period and Select Baseline
    driver.find_element_by_css_selector("input.linksubmit[value=\"▸ Time 
Period\"]").click()
    driver.find_element_by_css_selector("input.linksubmit[value=\"1961-
1990\"]").click()
    # Click on Geographic Areas Link
    driver.find_element_by_css_selector("input.linksubmit[value=\"▸ 
Geographic Areas\"]").click()
    # Unselect all countries
    driver.find_element_by_xpath('//*[@id="fieldareaList__pln-1"]').click()
    # Close tab for Northern Africa
    driver.find_element_by_xpath('//*[@id="rg1-66-Northern 
Africa"]/span').click()
    # Wait 1 second
    time.sleep(1)
    # Click geographic area then country
    driver.find_element_by_xpath('//label[text()="{}"]/following-
sibling::span'.format(geographic_area)).click()
    driver.find_element_by_xpath('//label[text()="
{}"]'.format(country)).click()
    # Click on Map Link
    driver.find_element_by_css_selector("input.linksubmit[value=\"▸ 
Map\"]").click()
    # Download Data
    driver.find_element_by_xpath('//*[@id="buttons"]/a[4]/img').click()

    # Wait 2 seconds
    time.sleep(2)

    # Download blah blah
    path = 'C:/.../Download'
    destination_folder = 'C:/.../CSV_Files'
    file_list = [os.path.join(path, f) for f in os.listdir(path)]
    time_sorted_list = sorted(file_list, key=os.path.getmtime)
    file_name = time_sorted_list[-1]
    # decompress the zipped file here
    myzip = zipfile.ZipFile(file_name)

    # Wait 1 second
    time.sleep(1)

    myzip.extract('data.asc', destination_folder)

    # Save data.asc file as .csv and rename reflects download selections
    newfilename = country + Crop + Water_Supply + Input_Level + AES_and_P
    df = pd.read_table(os.path.join(destination_folder, 'data.asc'), 
sep="\s+", skiprows=6, header=None)
    df.to_csv(os.path.join(destination_folder, '{}.csv'.format(newfilename)))

    # Delete downloaded data.asc file
    delete_data_file = "C:/.../CSV_Files/data.asc"
    # if file exists, delete it
    if os.path.isfile(delete_data_file):
        os.remove(delete_data_file)
    else:  # Show error
        print("Error: %s file not found" % delete_data_file)

    driver.close()

但是,此代碼只是在繼續時停止了該函數,沒有完成代碼的下載部分,而是遍歷了循環的其余部分。 有什么解決的辦法嗎? 另外,請讓我知道問題是否令人困惑。

經過評論中的討論,我相信至少可以看到您的問題的一部分。 python continue關鍵字並不表示“繼續執行其余的控制流”,而是表示“繼續執行循環的下一個迭代,之后跳過所有內容”。

例如,在下面的Python代碼中:

a = []
for i in range(10):
    if i == 5:
        continue
    a.append(i)

print(a)

結果將是:

[0, 1, 2, 3, 4, 6, 7, 8, 9]

而不是,使用您以前的邏輯

[5]

因此,要使代碼繼續運行,您需要翻轉邏輯,以便在條件不成立時跳過,例如:

 if not data_check[0].is_displayed():
     continue

盡管我個人從未遇到過與您犯過相同錯誤的人,但是我確實強調,從語義上講,“繼續”是指繼續執行該程序的下一部分,這似乎更有意義。 continue Python的選擇很大程度上來自歷史上對continue作為關鍵字的用法, 尤其是在C語言中 在這種情況下,我們可以看到continue為更多的擴展的break聲明為“跳過”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM