我正在尝试从网站中提取一些数据。然而,该网站具有层次结构。它的顶部有一个下拉菜单,其选项值为 URL。因此,我的方法是:
下面是我的代码,我能够在默认选择的选项(第一个)下提取数据。但我得到了错误
Message: Element not found in the cache - perhaps the page has changed since it was looked up
。我的浏览器似乎没有切换到新页面。我尝试过 time.sleep()
或 driver.refresh()
,但失败了...任何建议表示赞赏!
<select class="form-control">
<option value="/en/url1">001 Key</option>
<option value="/en/url2">002 Key</option>
</select>
# select the dropdown menu
select_box = Select(driver.find_element_by_xpath("//select[@class='form-control']"))
# get all options
options = select_box.options
for ele_index, element in enumerate(options):
# select a url
select_box.select_by_index(ele_index)
time.sleep(5)
print element.text
# extract page data
id_comp_html = driver.find_elements_by_class_name('HorDL')
for q in id_comp_html:
print q.get_attribute("innerHTML")
print "============="
# dropdown menu
select_box = Select(driver.find_element_by_xpath("//select[@class='form-control']"))
options = select_box.options
for ele_index in range(len(options)):
# select a url
select_box = Select(driver.find_element_by_xpath("//select[@class='form-control']"))
print select_box.options[ele_index].text
select_box.select_by_index(ele_index)
# print element.text
# print "======"
driver.implicitly_wait(5)
id_comp_html = driver.find_elements_by_class_name('HorDL')
for q in id_comp_html:
print q.get_attribute("innerHTML")
print "============="
您的
select_box
和 element
引用已过时,您必须在循环内操作选项索引时“重新查找”选择元素:
# select the dropdown menu
select_box = Select(driver.find_element_by_xpath("//select[@class='form-control']"))
# get all options
options = select_box.options
for ele_index in range(len(options)):
# select a url
select_box = Select(driver.find_element_by_xpath("//select[@class='form-control']"))
select_box.select_by_index(ele_index)
# ...
element = select_box.options[ele_index]
选择选项并提取所需数据后,您可能还需要导航回来。这可以通过
driver.back()
来完成。
从您对网站和代码的描述来看,似乎从下拉列表中选择一个选项会将您带到另一个页面;因此,在 for 循环中第一次迭代后,您已移至不同的页面,而您的
options
变量指向前一页中的元素。
针对您的情况(在这种情况下可能是最好的解决方案)的一种解决方案是存储选项值(即网址),并通过
.get()
方法直接导航到这些网址。
否则,您需要保留一个计数器并在每次迭代时获取下拉列表的内容,或在每次迭代后向后导航,在这种情况下这两种选择都是不必要的。