我正在尝试从网站中提取一些数据。然而,该网站具有层次结构。它的顶部有一个下拉菜单,其选项值为 URL。因此,我的方法是:
- 找到下拉框,
- 选择一个选项,
- 提取一些数据,并且
- 对所有可用选项重复步骤 2 至 4。
下面是我的代码,我能够在默认选择的选项(第一个选项)下提取数据。但我收到错误消息:在缓存中找不到元素 - 也许页面自查找以来已更改
。我的浏览器似乎没有切换到新页面。我尝试了 time.sleep()
或 driver.refresh()
,但失败了...任何建议表示赞赏!
###html
<select class="form-control">
<option value="/en/url1">001 Key</option>
<option value="/en/url2">002 Key</option>
</select>
### python code
# 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 "============="
更新1(基于alecxe的解决方案)
# 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()
来完成。
关于python - 使用 selenium python 从下拉框中选择每个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43751916/