selenium + python是一种比较通用的web自动化解决方案。
1、环境搭建:
windows环境:selenium + python、chromediver.exe驱动 + chrome浏览器。
注意:
chromediver.exe驱动 与 chrome浏览器必须配套,否则可能版本不兼容。
chromedriver.exe文件,直接放到python根目录下。
环境搭建:
https://www.cnblogs.com/yoyoketang/p/6789537.html?utm_source=itdadao&utm_medium=referral
2、指导手册,API:
python webdriver API:
selenium API文档:在线
http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement
python selenium api说明文档查看方法:离线
http://blog.csdn.net/freesigefei/article/details/50541413
Python-Selenium基本操作 API:入门
https://wenku.baidu.com/view/7879a74559fafab069dc5022aaea998fcc2240c3.html?from=search
selenium webdriver(python)第三版:全,作为指导手册
https://wenku.baidu.com/view/211fbafecc7931b764ce1550.html?from=search
3、元素定位:
在selenium中使用css选择器进行元素定位:http://blog.csdn.net/grace666/article/details/48419529
Selenium2+python自动化7-xpath定位:https://www.cnblogs.com/yoyoketang/p/6123938.html
Python selenium —— XPath and CSS cheat sheet:http://blog.csdn.net/huilan_same/article/details/52806985
Python selenium —— 父子、兄弟、相邻节点定位方式详解:http://blog.csdn.net/huilan_same/article/details/52541680
总结:
1、web自动化一半的工作是元素定位。dirver.find_element_by_css_selector()是一种通用的方法,速度快于find_element_by_xpath()
2、由于页面的复杂性、浏览器运行效率问题,元素定位和操作,经常导致不稳定情况出现,需要加等待时间。
Python selenium 三种等待方式详解:http://blog.csdn.net/ping523/article/details/53419622
time.sleep(3) # 强制等待3s
driver.implicitly_wait(30) # 隐性等待,最长等30秒。注意:全局起效的,不要当作sleep使用。
WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator)) #显示等待某条件。也可以自己实现函数,进行异常捕获,超时时间内尝试多次。
3、注意find_elements_by_css_selector和find_element_by_css_selector的区别。
find_elements_by_css_selector是获取webElement数组,用于获取一组元素。webElement可再次调用find_element_by_css_selector等,可以进行分层定位。
4、除了元素定位,可能会涉及到鼠标、键盘、元素和属性等操作:
[python爬虫] Selenium常见元素定位方法和操作的学习介绍:http://blog.csdn.net/Eastmount/article/details/48108259