How to get data from Ajax request in Selenium?

2019-07-29 05:19发布

问题:

I have been trying to check the balances of Starbucks gift cards in my application, https://www.starbucks.com/card

I was trying to catch the response made with ajax request, once check balance button is clicked automated, How can I get the ajax response in Selenium?

using (var driver = new ChromeDriver())
        {
            driver.Navigate().GoToUrl(@"https://www.starbucks.com/card");
            driver.FindElement(By.Id("Card_Number")).SendKeys("7848549479363805");
            driver.FindElement(By.Id("Card_Pin")).SendKeys("91435723");
            driver.FindElement(By.XPath("//button[.='Check Balance']")).Click();
        }

How can I read this response as I am unable to with above code?

Below is the Response after Ajax request:

<div id="cardBalanceWrapper">

<div id="card-balance-display" class=" region reset-left">
<img src="https://www.starbucks.com/images/cardimages/card_altdistcoreFY13_165.png" alt="Standard"></div>
    <div id="fetch_balance" class="region size1of3 reset">
    <strong>Card balance</strong>
<h2><span class="fetch_balance_value">$0.00</span></h2> <p>as of <span class="date">6/19/2017 6:56 PM</span></p></div>
<div class="fields region size1of1 reset-left">
<ul class="balance_links">

        <li><a href="/account/signin">Register This Card</a></li>

    <li><a href="/account/card/Reload">Reload This Card</a></li>
    <li><a href="/card/manage/history">View Card Transactions</a></li>
    <li><hr></li>
    <li><a href="/card?showdefault=False">Enter Another Card</a></li>
</ul>

回答1:

To fetch ajax requests you can use rest-assured
It is more fast and reliable way to get data. Do not use Selenium for such purposes.