python - Selenium HTMLUNIT Python 滚动页面

标签 python selenium htmlunit xpath

我有一个网站,当我向下滚动时会生成更多产品。与其他网站不同,在 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.

关于python - Selenium HTMLUNIT Python 滚动页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14731017/

相关文章:

javascript - 当对象不可调用时,如何使用 python selenium "click"?我这里需要 javascript 吗?如何?

java - 解析包含动态 javascript 对象的网页

java - Xpath 获取 href 标签中匹配文本的第二个 url

python - Pandas DatetimeIndex 与 to_datetime 差异

python - Flask 邮件错误 "SMTPServerDisconnected(' 请先运行 connect()')"

python - 使用 Pandas,如何使列表中的每个项目填充 pandas 列中的每个单元格

java - Htmlunit中点击按钮后如何刷新页面

python - 使用 Python 将 BMP/PNG/JPEG 转换为 SVG 文件

selenium - 自动关闭 Apple id 验证弹出窗口

javascript - 无法使用 Selenium( headless )检索 Javascript 图表背后的数据/数组