Python Selenium - 遍历搜索结果

时间:2016-10-13 12:27:37

标签: python selenium selenium-webdriver

在搜索结果中,我需要验证所有这些内容都必须包含搜索关键字。这是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

任何人请告诉我这是什么方法?谢谢!

2 个答案:

答案 0 :(得分:1)

您应该检查特定元素的innerHTML值是否包含键字符串,而不是元素本身,所以请尝试

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

答案 1 :(得分:0)

我在assert陈述中弄错了。

因为result是一个WebElement,所以没有要查找的文本。

我只需更改它:assert "Sunshine" in result.text