不懂,为什么onenote复制到csdn差异这么大
准备:为电脑安装chrome和chrome driver,配置环境变量
1.声明使用的浏览器对象
browser = webdriver.Chrome()
browser = webdriver.PhantomJS()
2.访问页面
browser.get('https://www.taobao.com')
3.查找元素
首个节点 find_element_by_**
所有节点 find_elements_by_**
xpath的情况有点特殊
driver.find_element_by_xpath('//button[@id="logout"]')
4.节点交互
- 输入文字时用send_keys()方法
input = browser.find_element_by_id('q')
input.send_keys('iPhone')
- 清空文字时用clear()方法
input.clear()
- 点击按钮时用click()方法
button = browser.find_element_by_class_name('btn-search')
button.click()
5.获取元素内容
获取属性
logo = browser.find_element_by_id('zh-top-link-logo')
print(logo.get_attribute('class'))
获取文本值
print(logo.text)
获取tag_name
print(logo.tag_name)
6.网页内容
driver.page_source #对它用beautifulsoup进一步处理
driver.title
driver.click
参考: https://cuiqingcai.com/5630.html
问题小节
- 对于click无效的问题
点击前加一行time.sleep(5)试试,亲测有效
- 网站 http://a.suda.edu.cn/ 在logout后会跳到一个新网站。这种变化driver无法维护需要重新加载( 在加一行driver.get('http://a.suda.edu.cn/') ),否则第三节的查找元素会出错误。而像在线时长这种时钟形式的变动则无需重新加载driver的。
- 出于效率考虑,在调试完成后,可以将浏览器引擎从chrome换成隐式的PhantomJS
- 好像没有查到通过多个属性标签定位一个元素的语法,一种方法是指定find_elements_by_**的index,如
elements = driver.find_elements("css selector", ".mnav")
print(elements[3].text)
或者遇到不定的情况,遍历elements通过第五节获得元素内容来逐个确认。