[译]Selenium Python文档:八、附录:FAQ常见问题

另外一个FAQ:https://github.com/SeleniumHQ/selenium/wiki/Frequently-Asked-Questions

8.1.怎样使用ChromeDriver

chromedriver 下载页下载版(译者注:需翻墙)。解压压缩包:

unzip chromedriver_linux32_x.x.x.x.zip

你应该看到一个chromedriver可执行文件。接着你就可以像下面这样创建一个WebDriver实例:

driver = webdriver.Chrome(executable_path="/path/to/chromedriver")

示例的其他部分参考其他文档中的介绍。

8.2.Selenium2支持XPATH2.0吗?

参考:http://seleniumhq.org/docs/03_webdriver.html#how-xpath-works-in-webdriver

Selenium使用的XPath取决于浏览器本身的XPath引擎。也就是说你使用的浏览器支持什么版本的XPath,Selenium就支持什么版本的XPath。如果使用不自带XPath引擎的浏览器(比如,IE5,7,8),Selenium将只支持XPath1.0。

8.3.怎样滚动到页面底部?

参考:http://blog.varunin.com/2011/08/scrolling-on-pages-using-selenium.html

你可以在加载页面的时候使用execute_script方法执行javascript代码。所以,你可以调用Javascript API滚动到页面的底部或其他任意位置。

下面是滚动到页面底部的示例:

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

DOM中的window对象有一个scroll方法,用来滚动到窗口的任意位置。scrollHeight是所有元素的一个通用属性。document.body.scrollHeight标识页面整个body的高度。

8.4.怎样使用地址的火狐配置文件自动保存文件?

参考-1:http://stackoverflow.com/questions/1176348/access-to-file-download-dialog-in-firefox

参考-2:http://blog.codecentric.de/en/2010/07/file-downloads-with-selenium-mission-impossible/

首先先识别你要保存的文件的文件类型。

要识别你要自动下载的文件的content-type,可以使用curl+grep命令:

curl -I URL | grep "Content-Type"

另外一种办法是使用requests模块来找到content-type,简单示例如下:

import requests
content_type = requests.head('http://www.python.org').headers['content-type']
print(content_type)

识别出content-type之后,你就可以使用它来设置火狐配置文件的配置:

browser.helperApps.neverAsk.saveToDisk

下面是一个小示例:

import os

from selenium import webdriver

fp = webdriver.FirefoxProfile()

fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir", os.getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream")

browser = webdriver.Firefox(firefox_profile=fp)
browser.get("http://pypi.python.org/pypi/selenium")
browser.find_element_by_partial_link_text("selenium-2").click()

在上面的示例中,content-type被设置为 application/octet-stream

browser.download.dir选项用来指定你想要将下载的文件保存的目录。

8.5.怎样通过file input上传文件?

选取<input type="file">元素,调用send_keys方法,给其传递一个文件路径(绝对路径和相对路径均可)。但是请注意Windows系统和Unix系统路径名称的差异。

8.6.怎样在火狐的Firefox?

首先下载FireBug XPI文件,接着你就可以调用add_extension方法来使用他了。

from selenium import webdriver

fp = webdriver.FirefoxProfile()

fp.add_extension(extension='firebug-1.8.4.xpi')
fp.set_preference("extensions.firebug.currentVersion", "1.8.4") #避免启动界面
browser = webdriver.Firefox(firefox_profile=fp)

8.7.怎样对当前窗口截图?

使用web'driver提供的save_screenshot方法:

rom selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.python.org/')
driver.save_screenshot('screenshot.png')
driver.quit()
原文地址:https://www.cnblogs.com/taceywong/p/6602888.html