Python3爬虫之 Selenium库的使用

这篇具有很好参考价值的文章主要介绍了Python3爬虫之 Selenium库的使用。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

今天在官网看了下Selenium库,总结了下常用的方法,直接上代码。(沈略环境搭建,网上多得是),新手建议去了解10分钟再来看这里的代码。

这里列举一下常用的查找元素方法:其实find_element_by_xpath是万能的。

单元素定位:

find_element_by_name
find_element_by_id
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector


find_element(By.ID,"kw")
find_element(By.NAME,"wd")
find_element(By.CLASS_NAME,"s_ipt")
find_element(By.TAG_NAME,"input")
find_element(By.LINK_TEXT,u"新闻")
find_element(By.PARTIAL_LINK_TEXT,u"新")
find_element(By.XPATH,"//*[@class='bg s_btn']")
find_element(By.CSS_SELECTOR,"span.bg s_btn_wr>input#su") 

多元素定位:

find_elements_by_name
find_elements_by_id
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector

返回的是list列表,用print(type(elements_name))即可看到它的类型是list。文章来源地址https://www.toymoban.com/news/detail-508396.html

from selenium import webdriver
import lxml.html
from selenium.webdriver.common.by import By
import time
from selenium.webdriver import ActionChains
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException

browser = webdriver.Chrome()


# 先梳理一下逻辑,在讲下xpath的使用,最后讲下常用方法。
'''
1、导入webdriver模块
2、通过该模块点出一个浏览器对象

3、通过浏览器对象点出连接——browser.get("")
5、通过浏览器对象点出当前页面的html标签内容——browser.page_source
6、通过浏览器对象点出要获取元素的方法来获取html标签——browser.find_element(By.ID,"q").click() or browser.find_element_by_id("q").click()
7、这里重点讲一下xpath的使用,因为其他的都简单,
        import lxml.html
        html1 = "html内容"
        selector = lxml.html.fromstring(html1)
        (1)、没有属性的标签可省略,属性都相同的标签可省略。
        (2)、属性以某字符串开头:xpath('//div[starts-with(@id,"test")]/text()')遍历即可。
        (3)、属性值包含相同字符串:把上面的starts-with改为contains遍历即可。
        
        (4)、获取子标签下的文字:lists_index=selector.xpath('//div[@class="useful"]')。info_list=lists_index[0].xpath('ul/li/text()')输出即可。
        (5)、获取不同标签下的文字:data=selector.xpath('//div[@id="test3"]')[0]。info=data.xpath('string(.)')输出即可。
        (6)、第四句的意思是,获取class为useful的div标签,以列表形式返回,第一个div为div[0],以此类推;后面那句也是以列表的形式返回文本数据。
               第五句的意思是,获取id为test3的div标签的第一个div;后面那句是返回这个div[0]标签下的所有文本内容。

'''
html1 = '''
<html>
    <head>
        <title>ceshi</title>
    </head>
    <body>
        <div class="useful">
            <ul>
                <li class="info">1</li>
                <li class="info">2</li>
                <li class="info">3</li>
                <li class="inf">4</li>
            </ul>
        </div>
        <div class = "useful">
            <ul>
                <li class="info">5</li>
                <li class="info">6</li>
            </ul>
        </div>
    </body>
</html>
'''
selector = lxml.html.fromstring(html1)
useful = selector.xpath('//div[@class="useful"]')
info_list = useful[0].xpath('ul/li/text()')
print(info_list)



# 打开知乎,滑到最底下,输出一句话
# browser.get("http://www.zhihu.com/explore")
# browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')
# browser.execute_script('alert("To Bottom")')

# 打开淘宝,输入ipad,删除后输入MakBook pro,点击搜索
# browser.get("http://www.taobao.com")
# input_str = browser.find_element_by_id('q')
# input_str.send_keys("ipad")
# time.sleep(1)
# input_str.clear()
# input_str.send_keys("MakBook pro")
# button = browser.find_element_by_class_name('btn-search')
# button.click()

# 打开一个网址,拖动滑块到吻合的地方
# url = "http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable"
# browser.get(url)
# browser.switch_to.frame('iframeResult')
# source = browser.find_element_by_css_selector('#draggable')
# target = browser.find_element_by_css_selector('#droppable')
# actions = ActionChains(browser)
# actions.drag_and_drop(source, target)
# actions.perform()

# 打开网页,获取元素touple,获取属性的值
# url = 'https://www.zhihu.com/explore'
# browser.get(url)
# logo = browser.find_element_by_id('zh-top-link-logo')
# print(logo)
# print(logo.get_attribute('class'))

# 获取ID,位置,标签名
# url = 'https://www.zhihu.com/explore'
# browser.get(url)
# input = browser.find_element_by_class_name('zu-top-add-question')
# print(input.id)
# print(input.location)
# print(input.tag_name)
# print(input.size)

# 切入到frame中以及切出来
# url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable'
# browser.get(url)
# browser.switch_to.frame('iframeResult')  # 切入
# source = browser.find_element_by_css_selector('#draggable')
# print(source)
# try:
#     logo = browser.find_element_by_class_name('logo')
# except NoSuchElementException:
#     print('NO LOGO')
#
# browser.switch_to.parent_frame()  # 切出
# logo = browser.find_element_by_class_name('logo')
# print(logo)
# print(logo.text)

# 隐式等待(等10秒钟后还没出现就报错)
# browser.implicitly_wait(10)
# browser.get('https://www.zhihu.com/explore')
# input = browser.find_element_by_class_name('zu-top-add-question')
# print(input)

# 显示等待(等待某个元素出现)
# browser.get('https://www.taobao.com/')
# wait = WebDriverWait(browser, 10)
# input = wait.until(EC.presence_of_element_located((By.ID, 'q')))  # 元素是否出现
# button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.btn-search')))  # 元素是否可点击
# print(input, button)
'''
常用的判断条件:
title_is 标题是某内容
title_contains 标题包含某内容
presence_of_element_located 元素加载出,传入定位元组,如(By.ID, 'p')
visibility_of_element_located 元素可见,传入定位元组
visibility_of 可见,传入元素对象
presence_of_all_elements_located 所有元素加载出
text_to_be_present_in_element 某个元素文本包含某文字
text_to_be_present_in_element_value 某个元素值包含某文字
frame_to_be_available_and_switch_to_it frame加载并切换
invisibility_of_element_located 元素不可见
element_to_be_clickable 元素可点击
staleness_of 判断一个元素是否仍在DOM,可判断页面是否已经刷新
element_to_be_selected 元素可选择,传元素对象
element_located_to_be_selected 元素可选择,传入定位元组
element_selection_state_to_be 传入元素对象以及状态,相等返回True,否则返回False
element_located_selection_state_to_be 传入定位元组以及状态,相等返回True,否则返回False
alert_is_present 是否出现Alert
'''

# 浏览器的前进和后退
# browser = webdriver.Chrome()
# browser.get('https://www.baidu.com/')
# browser.get('https://www.taobao.com/')
# browser.get('https://www.zhihu.com/explore')
# browser.back()
# time.sleep(1)
# browser.forward()
# browser.close()

# cookie操作
# browser.get('https://www.zhihu.com/explore')
# print(browser.get_cookies())  # 得到
# browser.add_cookie({'name': 'name', 'domain': 'www.zhihu.com', 'value': 'zhaofan'})  # 添加
# print(browser.get_cookies())
# browser.delete_all_cookies()  # 删除
# print(browser.get_cookies())

# 选项卡的切换
# browser.get('https://www.baidu.com')  # 去百度(卡一)
# browser.execute_script('window.open()')  # 打开新选项卡(卡二)
# print(browser.window_handles)
# browser.switch_to_window(browser.window_handles[1])  # 获得卡二 去淘宝
# browser.get('https://www.taobao.com')
# time.sleep(1)
# browser.switch_to_window(browser.window_handles[0])   # 获得卡一 去知乎
# browser.get('https://www.zhihu.com/explore')

# 异常处理
# 这里的异常比较复杂,官网的参考地址:
# http://selenium-python.readthedocs.io/api.html#module-selenium.common.exceptions

# 超时、没找到元素异常处理
# try:
#     browser.get('https://www.baidu.com')
# except TimeoutException:
#     print('Time Out')
# try:
#     browser.find_element_by_id('hello')
# except NoSuchElementException:
#     print('No Element')
# finally:
#     browser.close()

到了这里,关于Python3爬虫之 Selenium库的使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • python3 爬虫相关学习7:初步摸索使用 BeautifulSoup

    目录 1 一个爬图片pic的代码的例子 1.1 学习的原文章 1.2 原始代码的问题总结 问题1 问题2 问题3 其他问题 1.3 原始代码 2  直接在cmd里 python运行报错 和 处理 2.1 运行报错 2.2 报错原因: 没有提前安装这个bs4  模块 2.3 如何提前知道我的python环境下有没有安装bs4 或其他模块呢

    2024年02月08日
    浏览(31)
  • Python爬虫 —— urllib库的使用(get/post请求+模拟超时/浏览器)

    爬虫简介 :网络爬虫就是按照一定规则,自动抓取互联网信息的程序或脚本,由于互联网数据的多样性和资源的有限性,根据用户需求定向抓取相关网页并分析就是爬虫要做的工作 为什么我们把它称为爬虫(Spider)嘞?互联网就像是一张大网,而每一个网页就是这张大网上

    2023年04月13日
    浏览(29)
  • Python中selenium的玩法,小朋友看了都说学会了

    selenium提取数据 1. driver对象的常用属性和方法 2. driver对象定位标签元素获取标签对象的方法 3. 标签对象提取文本内容和属性值 selenium的其它使用方法 1. selenium标签页的切换 2. switch_to切换frame标签 3. selenium对cookie的处理 4. selenium控制浏览器执行js代码 5. 页面等待 6. selenium开启

    2024年04月14日
    浏览(61)
  • 下载python3.10版本pycharm仍显示python3.1以及官网如何下载旧版版本python

    第二节 安装Pycharm以及遇到的问题 目录 Day01新手小白学python 前言 一、pycharm下载安装 二、遇到的问题 1.下载的是python3.10版本仍显示python3.1 has reached its end-od-life and is no longer supported          2.官网如何下载旧版如3.9版本python         3.自定义安装路径 总结 安装Pycha

    2024年02月06日
    浏览(34)
  • 基于华为商城的抢单工具python3.9的selenium webdriver使用及打包

    本文基于华为商城的抢单工具,讲解一下python3.9的selenium webdriver使用,网上也有相关的资料,但在自己动手做的过程中还是遇到了一些波折,想拿出来跟大家一起分享。开篇先放个图: 主要从三个大方面说明:开发环境搭建、工程打包、过程中所遇问题整理 话不多说,从头

    2024年04月09日
    浏览(57)
  • Python爬虫【selenium的基础使用】

    一.本文背景及概要 笔者在Python爬虫的学习过程中接触selenium,惊觉此包的强大之处,便对学习的知识做个记录,方便日后需要时查看,同时也和读者分享。文中表述如有错误,敬请指正,感激不尽。 本文主要是对selenium的概要和一些基础的用法。特此说明:笔者学习的资料中

    2024年02月04日
    浏览(28)
  • Python爬虫之selenium库使用详解

    什么是Selenium selenium 是一套完整的web应用程序测试系统,包含了测试的录制(selenium IDE),编写及运行(Selenium Remote Control)和测试的并行处理(Selenium Grid)。Selenium的核心Selenium Core基于JsUnit,完全由JavaScript编写,因此可以用于任何支持JavaScript的浏览器上。 selenium可以模拟真

    2023年04月19日
    浏览(69)
  • Python爬虫之selenium的基础使用

    一.本文背景及概要 笔者在Python爬虫的学习过程中接触selenium,惊觉此包的强大之处,便对学习的知识做个记录,方便日后需要时查看,同时也和读者分享。文中表述如有错误,敬请指正,感激不尽。 本文主要是对selenium的概要和一些基础的用法。特此说明:笔者学习的资料中

    2024年02月07日
    浏览(27)
  • python爬虫selenium和ddddocr使用

    selenium实际上是web自动化测试工具,能够通过代码完全模拟人使用浏览器自动访问目标站点并操作来进行web测试。 通过python+selenium结合来实现爬虫十分巧妙。 由于是模拟人的点击来操作,所以实际上被反爬的概率将大大降低。 selenium能够执行页面上的js,对于js渲染的数据和

    2024年02月07日
    浏览(33)
  • Python爬虫-使用Selenium模拟百度登录

        前面我已经安装好了Selenium并模拟成功了一下打开百度页面并进行查询,让我这个python初学者信心倍增,今天再来试一试百度登录 把打开百度的代码放到构造方法中 ps:那个文件目录是用于后面滑块验证图片保存的。 点击右上角的“登录”按钮,打开登录框, 代码如下:

    2024年02月06日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包