我正在使用Chrome驱动程序提取数据。
我只停留在一点:我需要遍历整个列表(所有元素)。第一次起作用,我可以下载一个文件。
对于第二次迭代,它显示了StaleElementReferenceException错误,并且页面文档未附加元素。
如何更改循环以克服此错误?
答案 0 :(得分:0)
您可以尝试以下方法:
options = browser.find_elements_by_xpath(
'/html/body/form[2]/table/tbody/tr[1]/td[1]/select/option')
for option in options:
result = option.click()
...
请参阅文档:https://selenium-python.readthedocs.io/locating-elements.html#locating-by-xpath
答案 1 :(得分:0)
大概的问题是,单击选项会使更多选项出现。您可以执行类似的操作-生成一个生成器以产生以前未找到的所有元素,直到没有剩下尚未被看到的元素为止。 (似乎WebElement不可散列,因此不能直接存储在集合中,但可以通过其id
attributes进行唯一标识,但是当将新元素添加到页面时,您可能需要检查是否可行。)< / p>
def all_elements_by_xpath(xpath):
found = set()
while True:
found_new_ones = False
for element in browser.find_elements_by_xpath(xpath):
if element.id not in found:
found_new_ones = True
found.add(element.id)
yield element
if not found_any:
return
for element in all_elements_by_xpath('/html/body/form[2]/table/tbody/tr[1]/td[1]/select/option'):
element.click()
请注意,这将首先按页面上显示的顺序单击所有最初在页面上的元素,然后才单击在单击后出现的新元素。如果您想要不同的顺序,或者元素有时消失,则可以对其进行更改以每次都再次搜索元素,如下所示:
def all_elements_by_xpath(xpath):
found = set()
while True:
for el in browser.find_elements_by_xpath(xpath):
if el.id not in found:
found.add(element.id)
yield element
break
else:
return