如何使用python selenium缩小页面

She*_*nta 1 python selenium selenium-webdriver

我发现这是为java: -

WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));
Run Code Online (Sandbox Code Playgroud)

但是如何使用Python做到这一点?我想在获取请求后缩小一个级别.

小智 15

这可以为带有 selenium 的 Python 完成工作(-v 3.141.0)

driver = webdriver.Chrome(executable_path='...')
driver.get("www.stackoverflow.com")
driver.execute_script("document.body.style.zoom='50%'")
Run Code Online (Sandbox Code Playgroud)


小智 8

我也到处寻找使用硒缩小的解决方案,文档中没有提到任何内容。幸运的是,Firefox 驱动程序 (geckodriver) 在其 Github问题之一上有此内容

我已经简要介绍了如何缩小(和缩小),希望这最有意义(或者至少对我来说是这样)

#I'm sure this will be interchangeable with the Chrome driver too
 driver = webdriver.Firefox()
#Set the focus to the browser rather than the web content
 driver.set_context("chrome")
#Create a var of the window
 win = driver.find_element_by_tag_name("window")
#Send the key combination to the window itself rather than the web content to zoom out
#(change the "-" to "+" if you want to zoom in)
 win.send_keys(Keys.CONTROL + "-")
#Set the focus back to content to re-engage with page elements
 driver.set_context("content")
Run Code Online (Sandbox Code Playgroud)


Vau*_*ein 5

您可以在指定缩放级别的地方执行类似操作,如下所示:

例如,如果我body有一个<div id='values'>,我可以使用缩放div

from selenium import webdriver

def main():
    browser = webdriver.Chrome()
    browser.set_window_size(1000, 1000)
    browser.get("http://yoursite.com")
    browser.execute_script("$('#values').css('zoom', 5);")

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

或者只是尝试:

driver.execute_script("document.body.style.zoom='zoom %'")
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用 `driver.execute_script("window.scrollTo(0, X)")' 其中 `X` 是您要滚动的垂直位置。 (2认同)