1

我試圖訪問使用硒HTML,看起來像這樣一個下拉菜單:下拉菜單中硒 - Python 3中

<span class="k-pager-sizes k-label"> 
<span title="" class="k-widget k-dropdown k-header" unselectable="on" role="listbox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-owns="" aria-disabled="false" aria-readonly="false" aria-busy="false" aria-activedescendant="8e90d557-7e8d-4c5c-b906-202fd78c6d0a"><span unselectable="on" class="k-dropdown-wrap k-state-default"> 
<span unselectable="on" class="k-input">20</span><span unselectable="on" class="k-select"> 
<span unselectable="on" class="k-icon k-i-arrow-s">select</span> 
</span> 
</span> 
<select data-role="dropdownlist" style="display: none;"> 
<option value="10">10</option><option value="15">15</option> 
<option value="20">20</option><option value="50">50</option> 
<option value="100">100</option> 
</select> 
<span>items per page</span> 

我曾嘗試沒有成功如下:

try: 
    driver = webdriver.Chrome('/Users/opusandcaymus/Election/chromedriver') 
    driver.get('http://mcad-tx.org/Property-Search-Result?searchtext=Maple%20Branch') 
    #dropdown=driver.find_element_by_xpath('//*[@id="grid"]/div[3]/span[2]/span/select') 
    #select = Select(dropdown) 
    dropdown = driver.find_elements_by_tag_name("option") 
    for row in dropdown: 
     print(row.value) 
    driver.close() 
except: 
    print("error") 
    driver.close() 
    raise 

不任何人都知道如何通過值來找到選項?每次打開頁面時,我都想選擇100。

回答

1

你選擇下拉隱藏所以,我會建議先使用javascriptexecuter然後選擇相應的值下面的代碼

使用使其可見:

element=driver.find_element_by_xpath("//select[@data-role='dropdownlist']") 
driver.execute_script("arguments[0].setAttribute('style', 'display: block;')",element) 
select = Select(element) 
select.select_by_value("100") 

而另一種方法是使用Explicitwait 首先點擊然後點擊數值100

下面的代碼在Python中:

from selenium.webdriver.support import expected_conditions as EC 

wait = WebDriverWait(driver, 10) 
element = wait.until(EC.visibility_of_element_located((By.XPATH, ".//*[@id='grid']/div[3]/span[2]/span/span/span[2]/span"))) 
element.click 

element = wait.until(EC.visibility_of_element_located((By.XPATH, ".//ul[@data-role='staticlist']/li[5]"))) 
element.click 

注意:請根據python語法進行更正

+1

完美無瑕。謝謝你的答案。我仍然在學習如何在Python中使用Selenium中的JavaScript。很有幫助。 –