页面#2上的下一个按钮XPath更改,不会循环

时间:2018-05-27 07:08:01

标签: python selenium

我有一个脚本循环遍历标题的一系列元素,然后点击“下一步”加载下一系列要删除的元素。问题是“下一步”按钮的xpath在第2页上发生变化,很可能在第3页上发生。我不能使用按类查找或按ID查找,因为这些类/ ID名称不止一次出现。一旦找不到第二页上的“下一步”按钮,脚本就会出错。

while True: 
    deal_title = browser.find_elements_by_xpath("//a[@id='dealTitle']/span")
    titles = []
    for title in deal_title:
        titles.append(title.text)

    deal_link = browser.find_elements_by_xpath("//div[@class='a-row dealDetailContainer']/div/a[@id='dealTitle']")
    links = []
    for link in deal_link:
        links.append(link.get_attribute('href'))

    deal_image = browser.find_elements_by_xpath("//a[@id='dealImage']/div/div/div/img")
    images = []
    for image in deal_image:
        images.append(image.get_attribute('src'))

    deal_price = browser.find_elements_by_xpath("//div[@class='a-row priceBlock unitLineHeight']/span")
    prices = []
    for price in deal_price:
        prices.append(price.text)

    try:
        #clicks next button - this is the xpath for the page 1 button
        browser.find_element_by_xpath("//span[@class='a-declarative']/div[2]/ul/li[@class='a-last']/a").click()
    except NoSuchElementException:
    break

下面是第2页上下一个按钮的xpath:

browser.find_element_by_xpath("//span[@class='a-declarative']/div[1]/ul/li[@class='a-last']/a").click()

2 个答案:

答案 0 :(得分:0)

尝试替换

browser.find_element_by_xpath("//span[@class='a-declarative']/div[2]/ul/li[@class='a-last']/a").click()

browser.find_element_by_link_text("Next→").click()

答案 1 :(得分:0)

你可以把它们连在一起 browser.find_element_by_xpath(" //跨度[@class ='一个声明性'] / DIV [2] / UL /锂[@class =' A-最后'] / A | //跨度[@class ='一个声明性'] / DIV [1] / UL /锂[@class =' A-最后'] /一 &#34)点击()。  或者你可以写一个更通用的xpath //的Li [@class =' A-最后'] / A

相关问题