Skip to main content
 首页 » 编程设计

python之Selenium HTMLUNIT Python 滚动页面

2025年05月04日15freeliver54

我有一个网站,当我向下滚动时会生成更多产品。与其他网站不同,在 firebug 控制台中找不到任何东西。所以,我正在使用 selenium 来模拟浏览器。我已经让它工作了,但是使用了 firefox 驱动程序。但是,由于我正在托管在命令行上运行的 Web 服务器,因此我使用的是 HTMLUNIT。有人能告诉我如何使用 HTMLUNIT 滚动页面吗?这是到目前为止的代码:

from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
import time 
 
browser = webdriver.Remote("http://127.0.0.1:4444/wd/hub",desired_capabilities=webdriver.DesiredCapabilities.HTMLUNITWITHJS) 
browser.get("http://www.somewebsite.com/") 
x = browser.find_elements_by_xpath("//div[@id='containeriso3']/div/a[1]") 
hrefs = [i.get_attribute('href') for i in x] 
print len(hrefs) 
time.sleep(2) 
browser.execute_script("scroll(0, 2500);") 
time.sleep(2) 
x = browser.find_elements_by_xpath("//div[@id='containeriso3']/div/a[1]") 
hrefs = [i.get_attribute('href') for i in x] 
print len(hrefs) 

谢谢。

请您参考如下方法:

您可以使用 JavaScript 进行滚动。来自docs :

You can use the execute_script method to execute javascript on the loaded page. So, you can call the JavaScript API to scroll to the bottom or any other position of a page.

Here is an example to scroll to the bottom of a page:

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

The window object in DOM has a scrollTo method to scroll to any position of an opened window. The scrollHeight is a common property for all elements. The document.body.scrollHeight will give the height of the entire body of the page.