Selenium安装、使用及交互案例

1、selenium安装

  1. 浏览器下载selenium
    chrome下载网址:https://chromedriver.storage.googleapis.com/index.html
    注:需要下载和chrome浏览器版本和操作系统匹配的驱动
  2. python下载selenium
pip install selenium -i https://pypi.douban.com/simple

2、selenium基本使用

  1. 创建谷歌浏览器操作对象
service = Service("chromedriver.exe")
browser = webdriver.Chrome(service=service)
  1. 访问网址
url = 'https://www.baidu.com'
browser.get(url)

3、元素定位和元素信息

元素定位
格式:browser.find_element(By.XXX,‘xxx’)

应用实例:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

service = Service("chromedriver.exe")
browser = webdriver.Chrome(service=service)

url = 'https://www.baidu.com'
browser.get(url)

# 元素定位
# button = browser.find_element(By.XPATH,'//input[@id="su"]')
button = browser.find_element(By.ID,'su')
print(button)

# 获取元素的标签
print(button.get_attribute('class'))
# 获取标签的名字
print(button.tag_name)
# 省略......

4、交互

应用实例

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

# 创建浏览器对象
service = Service('chromedriver.exe')
browser = webdriver.Chrome(service=service)
# 访问的url
url = 'https://www.baidu.com'
browser.get(url)
time.sleep(2)

# 获取输入框对象
input = browser.find_element(By.ID,'kw')
# 在输入框中输入 邓紫棋
input.send_keys('邓紫棋')
time.sleep(2)

# 获取百度一下的按钮
button = browser.find_element(By.ID,'su')
# 点击百度一下按钮
button.click()
time.sleep(2)

# 滑到浏览器底部
js_bottom = 'document.documentElement.scrollTop=100000'
browser.execute_script(js_bottom)
time.sleep(2)

# 获取下一页按钮
next = browser.find_element(By.XPATH,'//a[@class="n"]')
# 点击下一页
next.click()
time.sleep(2)

# 回到上一页
browser.back()
time.sleep(2)

# 回去
browser.forward()
time.sleep(3)

# 退出浏览器
browser.quit()

5、无界面浏览器(chrome handless)

应用实例:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def share_browser():
    # 初始化
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')

    path = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
    chrome_options.binary_location = path

    browser = webdriver.Chrome(chrome_options=chrome_options)
    # 以上代码都是写死的,只需要改 path为自己浏览器位置
    return browser

url = 'https://www.baidu.com'
browser = share_browser()
browser.get(url)
# 拍照片,看是否访问了目标网址
browser.save_screenshot('baidu.png')
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

京茶吉鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值