如何使用python selenium缩小页面

2024-05-13 10:01:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在爪哇找到这个:

WebElement html = driver.findElement(By.tagName("html"));
html.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD));

但是如何使用Python来实现这一点呢?我想在收到请求后缩小一个级别。


Tags: addbyhtmldriverkeys级别controlchord
3条回答

我到处寻找使用selenium缩小范围的解决方案,文档中没有提到任何内容。幸运的是,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")

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

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

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()

或者尝试一下:

driver.execute_script("document.body.style.zoom='zoom %'")

这对IE有效

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Ie(executable_path=path_to_driver, capabilities={'ignoreZoomSetting':True})
driver.get(url)
driver.find_element_by_tag_name('html').send_keys(Keys.CONTROL, '0')

相关问题 更多 >