Python爬虫selenium的安装和使用

selenium的安装:

pip install selenium

浏览器驱动下载

Chrome:https://sites.google.com/a/chromium.org/chromedriver/downloads
Edge:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Firefox:https://github.com/mozilla/geckodriver/releases
Safari:https://webkit.org/blog/6900/webdriver-support-in-safari-10/

下载后将安装目录添加至环境变量

640?wx_fmt.png

 打开Pycharm进行测试:

from selenium import webdriver         #导入web驱动模块
 
driver = webdriver.Chrome()            #创建Chrome驱动
driver.get("https://www.baidu.com")
 
input = driver.find_element_by_css_selector('#kw')#找到输入框
input.send_keys("Xylon")        #搜索内容
 
button = driver.find_element_by_css_selector('#su')#找到搜索按钮
button.click()

结果:

 

selenium的使用:

1 Chrome 配置

options = webdriver.ChromeOptions()
## 无界面
# options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=options)
driver.set_window_size(1366, 768)
driver.set_page_load_timeout(self.timeout)

注意Chrome可能需要管理员权限相关配置

2 Firefox 配置

# 实例化参数对象
options = webdriver.FirefoxOptions()
# 无界面
# options.add_argument('--headless')
driver = webdriver.Firefox(firefox_options=options)
driver.set_window_size(1400, 700)
driver.set_page_load_timeout(self.timeout)

3 不显示打开浏览器的界面
有的时候我们不想要看到爬取的一步步操作,只关心结果,则可以在参数配置

# 无界面
options.add_argument('--headless')

4 禁用浏览器弹窗
不是页面弹窗,是浏览器设置里的弹窗。在打开浏览器时,使用参数配置关闭
Firefox

options.set_preference('dom.webnotifications.enabled', False)
options.set_preference('dom.push.enabled', False)

Chrome

 prefs = {
     'profile.default_content_setting_values': {
         'notifications': 2
     }
 }
 options.add_experimental_option('prefs', prefs)

5 driver属性和方法
页面加载

driver.get("http://www.baidu.com")

关闭浏览器

# 爬虫结束关闭浏览器
driver.close()

获取当前url

driver.current_url

刷新

driver.refresh()

页面标题

driver.title

页面渲染后的源码

driver.page_source

获取窗口信息

driver.get_window_rect()

获取当前窗口的x,y坐标和当前窗口的高度和宽度,如:{‘height’: 1366, ‘width’: 768, ‘x’: 0, ‘y’: 200}

设置 User Agent(Firefox为例)

profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "some UA string")
driver = webdriver.Firefox(profile=profile)

执行js脚本

使用driver.execute_script([js脚本],*args)同步执行,如滑动到第一个class为cm-explain-bottom的元素位置。

driver.execute_script(
   "document.getElementsByClassName('cm-explain-bottom')[0].scrollIntoView(true)")

异步执行使用driver.execute_async_script([js脚本],*args),*argsw为执行js代码要传入的参数。

查找元素

返回一个WebElement对象。

通过id属性:element = driver.find_element_by_id("coolestWidgetEvah")
通过class属性:cheeses = driver.find_elements_by_class_name("cheese")
通过标签名:frame = driver.find_element_by_tag_name("iframe")
通过css选择器:cheese = driver.find_element_by_css_selector("#food span.dairy.aged")
通过name属性:cheese = driver.find_element_by_name("cheese")
通过xpath:inputs = driver.find_elements_by_xpath("//input")
通过链接文本(完全匹配):cheese = driver.find_element_by_link_text("cheese")
通过链接文本(部分匹配):cheese = driver.find_element_by_partial_link_text("cheese")

元素(WebElement)的属性和方法

标签下文本:element.text
点击:element.click()
表单提交:element.submit()
输入:element.send_keys(123)

示例:

# 等待邮箱和密码可定位及登录按钮可提交,清空输入框,分别输入用户名密码点击提交按钮
email = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#email")))
passwd = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#pass")))
submit = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#loginbutton')))
email.clear()
passwd.clear()
email.send_keys(user)
passwd.send_keys(password)
submit.click()

Cookie操作

driver.get("http://www.example.com")
# 给当前url域设置cookie
# name的值对应cookie key,value的值对应cookie value
driver.add_cookie({'name':'key', 'value':'value', 'path':'/'})
# 可选的属性
# 'domain' -> String,
# 'secure' -> Boolean,
# 'expiry' -> Milliseconds since the Epoch it should expire.

# 输出当前url所有的Cookie
for cookie in driver.get_cookies():
    print "%s -> %s" % (cookie['name'], cookie['value'])

# 通过name删除Cookie
driver.delete_cookie("CookieName")
# 删除所有的Cookie
driver.delete_all_cookies()

切换页面框架或窗口

driver.switch_to.window("windowName")

切换默认框架:

driver.switch_to.default_content()

切换最新窗口:

windows = driver.window_handles

切换到最新打开的窗口中

switch_to.window(windows[-1])

获取最新的alert弹窗

alert = driver.switch_to.alert
# 关闭弹窗
alert.dismiss()

当前的url返回或者跟进

driver.forward()
driver.back()

截屏

# 返回页面的base64编码字符串
base64 = driver.get_screenshot_as_base64()
# 返回保存到文件的结果
result = driver.get_screenshot_as_file("D:\\example.png")
# png格式的二进制字符串
pngSrc =  driver.get_screenshot_as_png()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值