python - 使用 Python 进行网页抓取 : How to scroll into a view by pixels?

标签 python selenium web-scraping beautifulsoup

我正在使用 Python 和 Selenium。我希望在 View 内按像素滚动,而不是按元素滚动。重点是循环直到我滚动到列表末尾。作为训练,我一直在尝试滚动所有喜欢这个 Instagram 帖子的人的列表:https://www.instagram.com/p/BuT_u-UAKn1/ 。我知道如何按元素滚动:

elements = driver.find_elements_by_xpath("//*[@id]/div/a")
driver.execute_script("return arguments[0].scrollIntoView();", elements[-1])

但我想按像素滚动。我尝试执行以下操作:

driver.execute_script("return arguments[0].scrollIntoView(true);", elements)
driver.execute_script("window.scrollBy(0,200);")

这样做时,会出现以下错误:

JavascriptException: Message: TypeError: arguments[0].scrollIntoView is not a function

有人知道如何按像素滚动到 View 中吗? 谢谢

最佳答案

以下内容对我有用。

#first move to the element
self.driver.execute_script("return arguments[0].scrollIntoView(true);", element)
#then scroll by x, y values, in this case 10 pixels up
self.driver.execute_script("window.scrollBy(0, -10);")

当你说滚动(0,200)时。正数表示向下滚动。如果要向上滚动,请使用负数-200

另请参阅此处的文档:https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy

如果您使用的浏览器不支持scrollToOptions,请切换到更好、更受支持的浏览器。

另一种可能的解决方案是实现 webDriverWait 以使特定元素在 HTML DOM 中可见

element = WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "element_css")))
self.driver.execute_script("return arguments[0].scrollIntoView(true);", element)

您也尝试使用 ActionChains

element = driver.find_element_by_id("id") # the element you want to scroll to 
ActionChains(driver).move_to_element(element).perform()

移动到元素后,就可以使用滚动代码

您还可以尝试添加偏移量。如果您一直向下滚动到底部,某些网页将不会加载新内容。有些网页仅在您到达页面末尾时才加载新内容。

document.documentElement.scrollHeight-10

一种不太传统的方法是在代码中执行 javascript。 还可以尝试使用 selenium 来最大化您的窗口。有时窗口的大小会影响Selenium的运行

driver.maximize_window()

findThis = driver.find_element_by_css_selector("CSS SELECTOR HERE")

jsScript = """
        function move_up(element) {
            element.scrollTop = element.scrollTop - 1000;
        }

        function move_down(element) {
            console.log('Position before: ' + element.scrollTop);
            element.scrollTop = element.scrollTop + 1000;
            console.log('Position after: ' + element.scrollTop);
        }

        move_up(arguments[0]);
        """
driver.execute_script(jsScript, findThis)

关于python - 使用 Python 进行网页抓取 : How to scroll into a view by pixels?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54989615/

相关文章:

python - 无法修改函数以独立工作而不是依赖于返回的结果

ios - 如何将 .ics 文件发布到我的 iPhone 日历中?

python - 使用 tornado web 服务器运行 hello world 时出现问题(Python 2.5,Windows 7)

python - 如何在 python 中为长名称选择合适的变量名

c# - 无法初始化 WebDriver Chrome 并且所有测试均失败

c# - MSTest 中数据驱动测试的问题

验证测试 : how to validate a UI?

python - Scrapy CrawlerProcess 不使用 CrawlSpider 保存数据

python - 如何克隆 PyPI 存储库并维护为本地存储库

python - S4 对象中的属性装饰器 (R)