簡體   English   中英

Python Selenium-遍歷搜索結果

[英]Python Selenium - iterate through search results

在搜索結果中,我需要驗證它們是否都必須包含搜索關鍵字。 這是HTML源代碼:

<div id="content">
    <h1>Search Results</h1>
    <a id="main-content" tabindex="-1"></a>     
        <ul class="results">

                <li><img alt="Icon for Metropolitan trains" title="Metropolitan trains" src="themes/transport-site/images/jp/iconTrain.png" class="resultIcon"/> <strong>Stop</strong> <a href="/next5/diva/10001218/1">Sunshine Railway Station (Sunshine)</a></li>

                <li><img alt="Icon for Metropolitan trains" title="Metropolitan trains" src="themes/transport-site/images/jp/iconTrain.png" class="resultIcon"/> <strong>Stop</strong> <a href="/next5/diva/10001003/1">Albion Railway Station (Sunshine North)</a></li>                
        </ul>       
</div>

我已經編寫了以下代碼來輸入搜索關鍵字並獲取結果,但是它無法遍歷搜索結果:

from selenium import webdriver

driver = webdriver.Chrome('C:/Users/lovea/OneDrive/Documents/Semester 2 2016/ISYS1087/w3-4/chromedriver')

driver.get('http://www.ptv.vic.gov.au')

next5Element = driver.find_element_by_link_text('Next 5 departures')
next5Element.click()

searchBox = driver.find_element_by_id('Form_ModeSearchForm_Search')
searchBox.click()
searchBox.clear()
searchBox.send_keys('Sunshine')

submitBtn = driver.find_element_by_id('Form_ModeSearchForm_action_doModeSearch')
submitBtn.click()

assert "Sorry, there were no results for your search." not in driver.page_source

results = driver.find_elements_by_xpath("//ul[@class='results']/li/a")
for result in results:
    assert "Sunshine" in result //Error: argument of type 'WebElement' is not iterable

有人告訴我實現此目標的正確方法是什么? 謝謝!

您應該檢查特定元素的innerHTML值是否包含鍵字符串,但不包含元素本身,因此請嘗試

for result in results:
    assert "Sunshine" in result.text

我在assert犯了一個錯誤。

因為result是一個WebElement,所以沒有要查找的文本。

我只是將其更改為: assert "Sunshine" in result.text

暫無
暫無

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

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