Python爬虫之Selenium库的基本使用方法

关于Selenium

  • Selenium是一个用于测试网站的自动化测试工具
  • 一款任何网站都能抓取的爬虫工具

Selenium的基本使用

  • 常用的查找元素方法:
方法 说明
find_element_by_name 通过name属性定位
find_element_by_id 通过id属性定位
find_element_by_xpath 通过xpath公式匹配定位
find_element_by_link_text 文字链接
find_element_by_partial_link_text 文字链接
find_element_by_tag_name 通过tag定位
find_element_by_class_name 通过class属性定位
find_element_by_css_selector 通过css样式属性定位
  • 基本流程
  1. 运用selenium启动chrome并载入指定页面

  2. 页面元素查找(多种查找方式:find_element_*)

  3. 内容填充(send_keys)

  4. iframe与父页面切换(switch_to_frame是切换到iframe,switch_to_default_content是切换到主页面)

  5. 浏览器交互处理:window.alert, window.confirm, window.prompt
        与上面的三个浏览器交互内容,需要用到switch_to_alert,有几个用法需要注意:
        a)accept():发送确定指令,相当于点击“确定”按钮
        b)dismiss():取消操作,相当于点击“取消”按钮或点击右上角“关闭”
        c)send_keys:填充prompt框需要填写的内容

  • 代码示例
# 引入selenium模块
from selenium import webdriver

# 启动chrome并载入注册页面
bs = webdriver.Chrome()
bs.get(web_url)

# 查找输入框(用户名、密码、电子邮件)和按钮(提交注册),并填充指定内容
# 由于表单内容是嵌在iframe里的,所以需要查找指向至iframe
# 如果又想跳出iframe,回到父页面,可以使用 bs.switch_to_default_content()
bs.switch_to_frame('register-iframe')
 
# 由于所有的元素都命名了id,可以使用find_element_by_id,还有很多的其它find_element_*大家可以练习
# 查找用户名框,并填充"myaccount"
account = bs.find_element_by_id('txt_account')
account.send_keys('myaccount')
 
# 查找密码框,并填充"pwd123"
pwd = bs.find_element_by_id('txt_password')
pwd.send_keys('pwd123')
 
# 查找电子邮箱框,并填充"[email protected]"
email = bs.find_element_by_id('txt_email')
email.send_keys('[email protected]')
 
# 查找提交按钮,并模拟点击提交
btn_reg = bs.find_element_by_id('btn_register')
btn_reg.click()

# 非常顺利的,完成了表单的填充和提交。一般的表单,由于涉及到数据的操作,开发人员都会设置一些二次确认以防止误操作。此处就是用了简单的confirm来进行二次确认,下面是如何让selenium来识别出confirm框,并点击“确定”按钮
# 将查找对象转移至confirm
confirm = bs.switch_to_alert()
 
# 点击确定按钮
confirm.accept()
如果要取消,使用confirm.dismiss()
如果是prompt,则可以使用send_keys()先填充内容,再调用accept()或dismiss()

# 关闭浏览器
bs.close()

chromedriver的安装

  • 使用selenium调用chrome浏览器需要使用chromedriver

  • 首先需要下载Chromedriver载后得到的是一个chromedriver.exe文件,chromedriver下载地址: http://npm.taobao.org/mirrors/chromedriver/

  • 将chromedriver.exe拷贝到chrome浏览器(C:\Program Files (x86)\Google\Chrome\Application)、python(C:\Program Files (x86)\Python36-32)安装根目录的路径下即可,这样就可以使用selenium启动谷歌Chrome浏览器

  • Tip:使用的chromedriver要和chrome浏览器的版本需要匹配,否则会出现错误。

猜你喜欢

转载自blog.csdn.net/weixin_44008788/article/details/108240495