Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

python - Force Selenium to wait for AngularJS

How can I force python Selenium wait for a second until AngularJS completes page parsing and loads some stuff that it needs.

Or how can I force Selenium to wait for 1 second after button click, which causes ajax request to the server, handled by AngularJS. I need server side actions to take place before navigating to other page.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If some asynchronous behavior in your application is important enough that a real user should wait for it, then you should tell them. Similarly, your script can wait for that same indication before proceeding.

For example, if a user clicks a button that triggers an API call to create a record, and the user needs to wait for that record to be created, you should show them a message indicating when it completes successfully, e.g., "Record created successfully." Your script can then wait for that same text to appear, just as a user would.

Importantly, it shouldn't matter how your application is implemented. What matters is that your users can use your application—not that it calls certain AngularJS APIs or React APIs, etc.

1. Using Selenium

Selenium includes WebDriverWait and the expected_conditions module to help you wait for particular conditions to be met:

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

TIMEOUT = 5

# ...

WebDriverWait(driver, TIMEOUT).until(
    EC.text_to_be_present_in_element(
        [By.CLASS_NAME, "alert"],
        "Record created successfully"))

2. Using Capybara (which uses Selenium)

As you can see above, bare Selenium is complicated and finicky. capybara-py abstracts most of it away:

from capybara.dsl import page

# ...

page.assert_text("Record created successfully")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...