我知道元素可能会刷新,但我仍然在找到旧元素。但是,我不知道如何修改它!请帮忙!
import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
driver = webdriver.Firefox()
driver.get("http://www.boci-pru.com.hk/english/mpf/mpfdisclaimer.aspx?to=http://www.boci-pru.com.hk/english/mpf/prices.aspx")
driver.find_element_by_xpath('//input[@value="I agree and wish to proceed"]').click()
driver.get("http://www.boci-pru.com.hk/english/mpf/prices_hist.aspx")
date = datetime.date.today() - datetime.timedelta(days=30)
fromday = Select(driver.find_element_by_xpath('//select[@name="fromday"]'))
frommonth = Select(driver.find_element_by_xpath('//select[@name="frommonth"]'))
fromyear = Select(driver.find_element_by_xpath('//select[@name="fromyear"]'))
fromyear.select_by_value(str(date.year))
frommonth.select_by_value(str(date.month))
fromday.select_by_value(str(date.day))
selFund = driver.find_element_by_xpath('//select[@name="selFund_code"]')
all_funds = selFund.find_elements_by_tag_name("option")
all_funds = [f for f in all_funds if len(f.get_attribute("value")) >= 2 and len(f.get_attribute("value")) < 6]
for fund in all_funds:
fund.click() # <--- this is where the issue starts
print(fund.get_attribute("value"))
driver.find_element_by_xpath('//input[@name="go"]').click()
答案 0 :(得分:0)
如果在单击“go”按钮后刷新元素,则必须再次find
元素 - 可能有更好的方法,但是代码的最直接修改将是像这样:
i = 0;
while True:
selFund = driver.find_element_by_xpath('//select[@name="selFund_code"]')
all_funds = selFund.find_elements_by_tag_name("option")
all_funds = [f for f in all_funds if len(f.get_attribute("value")) >= 2 and len(f.get_attribute("value")) < 6]
try:
all_funds[i].click()
print(fund.get_attribute("value"))
driver.find_element_by_xpath('//input[@name="go"]').click()
i += 1
except IndexError: # if i > len(all_funds)
break
假设选项的顺序在迭代之间没有变化..
答案 1 :(得分:-2)
使用&#34;尝试&#34;和&#34;除了&#34;阻止如下所示:
for fund in all_funds:
try:
fund.click()
print(fund.get_attribute("value"))
except:
driver.find_element_by_xpath('//input[@name="go"]').click()