【问题标题】:Scroll down pages with selenium and python使用 selenium 和 python 向下滚动页面
【发布时间】:2016-05-05 13:34:56
【问题描述】:

这就是问题所在:

我正在使用 selenium 从这个网页(“https://www.rockethub.com/projects”)下载所有成功的项目。如果单击任何按钮,则 url 不会更改。 我对成功的项目感兴趣,因此我单击按钮状态,然后单击成功。

在此页面上,我需要重复向下滚动以显示其他网址。 这是问题所在。到目前为止,我一直无法向下滚动页面

这是我的代码:

from selenium.webdriver import Firefox
from selenium import webdriver



url="https://www.rockethub.com/projects"

link=[]

wd = webdriver.Firefox()
wd.get(url)

next_button = wd.find_element_by_link_text('Status')
next_button.click()

next_but = wd.find_element_by_link_text('Successful')
next_but.click()

wd.execute_script("window.scrollTo(0, document.body.scrollHeight);")

你知道如何解决这个问题吗?

谢谢

詹吉

【问题讨论】:

  • 你的操作系统是什么?你用的是什么版本的python?
  • 我使用 Windows; Python 的版本是 3.4

标签: python-3.x selenium web-scraping


【解决方案1】:

由于内容是动态更新的,所以需要等待内容发生变化后再执行下一步:

class element_is_not(object):
    """ An expectation for checking that the element returned by
    the locator is not equal to a given element.
    """

    def __init__(self, locator, element):
        self.locator = locator
        self.element = element

    def __call__(self, driver):
        new_element = driver.find_element(*self.locator)
        return new_element if  self.element != new_element else None


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)

driver.get("https://www.rockethub.com/projects")

# get the last box
by_last_box = (By.CSS_SELECTOR, '.project-box:last-of-type')
last_box = wait.until(element_is_not(by_last_box, None))

# click on menu Status > Successful
driver.find_element_by_link_text('Status').click()
driver.find_element_by_link_text('Successful').click()

# wait for a new box to be added
last_box = wait.until(element_is_not(by_last_box, last_box))

# scroll down the page
driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")

# wait for a new box to be added
last_box = wait.until(element_is_not(by_last_box, last_box))

【讨论】:

  • 谢谢!这有很大帮助。代码运行良好,解释清楚。
【解决方案2】:

在循环中运行wd.execute_script("window.scrollTo(0, document.body.scrollHeight);"),因为每次执行脚本时只取回一定数量的数据,所以你必须在循环中执行它。

如果您只是想一次检索所有成功的项目并且对模拟向下滚动到页面不感兴趣,请查看this answer,它可能会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多