TypeError: 'FirefoxWebElement' object is not iterable error cycling through pages on a dynamic webpage with Selenium

TypeError: 'FirefoxWebElement' object is not iterable error cycling through pages on a dynamic webpage with Selenium

这是我要抓取的site

我想抓取第一页table中的所有信息:

然后点击第二个并做同样的事情:

以此类推,直到第51页。我知道怎么用selenium点击第二页:

link = "http://www.nigeriatradehub.gov.ng/Organizations"
driver = webdriver.Firefox()
driver.get(link)
xpath = '/html/body/form/div[3]/div[4]/div[1]/div/div/div[1]/div/div/div/div/div/div[2]/div[2]/span/a[1]'
find_element_by_xpath(xpath).click()

但我不知道如何设置代码以使其循环遍历每一页。我获取 xpath 的过程首先是一个手动过程(我继续使用 Firefox,检查该项目并将其复制到代码中),所以我不知道如何自动执行该步骤本身然后以下。

我尝试在网页中更上一层楼 html 并选择包含我想要的元素的整个页面部分,然后循环浏览它们,但这不起作用,因为它是 Firefox 网络对象(见下文)。这是页面源代码相关部分的快照:

通过像这样调用更高 class 的 xpath:

path = '//*[@id="dnn_ctr454_View_OrganizationsListViewDataPager"]'
driver.find_element_by_xpath(path)

并尝试看看我是否可以循环通过它:

for i in driver.find_element_by_xpath(path):
    i.click()

我收到以下错误:

如有任何建议,我们将不胜感激。

这个错误信息...

...意味着您正在尝试遍历 ,其中只有 list 对象是可迭代的。


解决方案

for() 循环中创建一个 list 来遍历它的元素,而不是使用 find_element* 你需要使用 find_elements*。所以你的有效代码块将是:

for i in driver.find_elements_by_xpath(path):
    i.click()