如何为多个页面重复工作代码?

时间:2019-05-21 07:42:45

标签: python selenium-webdriver

我正在尝试浏览许多页面,我知道这很容易做到,但是我是python的新手。

我的代码在单个页面上起作用,它进入下一页,我只需要以某种方式再次重复该过程,直到最后一页。

driver.get("www.example.com")
titles = driver.find_elements_by_css_selector("div.name")
for title in titles:
    print(title.text)
driver.execute_script("window.scrollTo(0, 4000)")
driver.find_element_by_xpath('//a[contains(@title,"Next Page")]').click()

该网站有65个页面,我想从所有页面中获取标题。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用while循环。在显示“下一页”按钮时,请执行以下操作:

driver.get("www.example.com")
titles = []
while (len(driver.find_elements_by_xpath('//a[contains(@title,"Next Page")]'))>0)
    titles.append(driver.find_elements_by_css_selector("div.name"))
    for title in titles:
        print(title.text)
    driver.execute_script("window.scrollTo(0, 4000)")
    driver.find_element_by_xpath('//a[contains(@title,"Next Page")]').click()
    WebDriverWait(driver, 30).until(expected_conditions.presence_of_element_located(('some-element')))

点击下一页后,我添加了一个等待条件。 “某些元素”部分表示一个可见的元素,向用户发出信号,表明页面已准备就绪。您可以根据需要进行更改。