【问题标题】:Selenium click on a next-page link not loading the next pageSelenium 单击下一页链接不加载下一页
【发布时间】:2018-01-06 04:57:44
【问题描述】:

我是 selenium 和网络抓取的新手,我正在尝试从以下链接获取信息:https://www.carmudi.com.ph/cars/civic/distance:50km/?sort=suggested

这是我正在使用的代码的 sn-p:

while max_pages > 0:
                results.extend(extract_content(driver.page_source))
                next_page = driver.find_element_by_xpath('//div[@class="next-page"]')
                driver.execute_script('arguments[0].click();', next_page)
                max_pages -= 1

当我尝试打印结果时,我总是从第 1 页获得 (max_pages) 个相同的结果。“下一页”按钮在页面中可见,当我尝试查找同一类的元素时,它只显示1个元素。当我尝试通过确切的 xpath 获取元素并对其执行单击操作时,它不起作用。我将它包含在一个 try-except 块中,但没有错误。为什么会这样?

【问题讨论】:

  • 为什么要使用 execute_script 而不要只使用 next_page.click()
  • @EduardFlorinescu 这样当我选择链接的父元素并单击时。

标签: python html selenium xpath web-crawler


【解决方案1】:

你让这变得比它需要的更复杂。在这里使用 JS 点击是没有意义的……只需使用普通的 Selenium 点击即可。

while True:
    # do stuff on the page
    next = driver.find_element_by_css_selector("a[title='Next page']")
    if next
        next.click()
    else
        break

【讨论】:

    【解决方案2】:

    替换:

    next_page = driver.find_element_by_xpath('//div[@class="next-page"]')
    driver.execute_script('arguments[0].click();', next_page)
    

    与:

    driver.execute_script('next = document.querySelector(".next-page"); next.click();')
    

    如果您在控制台中尝试next = document.querySelector(".next-page"); next.click();,您会看到它有效。

    【讨论】:

    • 这确实有效。但是,当循环多次(我尝试 10 次)时,它不会以相同的量加载它。 (我尝试了 1 个)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2018-12-08
    相关资源
    最近更新 更多