首页 > 其他分享 >selenium使用

selenium使用

时间:2022-11-25 20:35:15浏览次数:28  
标签:res time selenium bro 使用 import find

bs4搜索文档树

from bs4 import BeautifulSoup
import re

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my p" class="title">asdfasdf<b id="bbb" class="boldest">The Dormouse's story</b>
</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
soup = BeautifulSoup(html_doc, 'lxml')
1. 5种搜索方式:字符串、正则表达式、列表、True、方法

1.1 字符串:可以按照标签名、属性名查找、文本内容查找
res = soup.find(name='a', id='link2')
res = soup.find(href='http://example.com/tillie')
res = soup.find(class_='story')
res = soup.body.find('p')
res = soup.body.find(string='Elsie')
res = soup.find_all(attrs={'href': re.compile('^http')})
print(res)

1.2 正则表达式  标签名,属性可以使用正则匹配
res = soup.find_all(name=re.compile('^b'))
res = soup.find_all(href=re.compile('^http'))
for item in res:
    url = item.attrs.get('href')
    print(url)
# request-html    获取到页面中所有的链接地址
res = soup.find(attrs={'href': re.compile('^a')})
print(res)

1.3 列表  标签名,属性名  等于列表  或条件
res = soup.find_all(class_=['story', 'sister'])  # 或条件
res = soup.find_all(name=['a', 'p'])  # 或条件
print(res)

1.4 True  标签名,属性名  等于布尔
res = soup.find_all(name=True)  # 有标签名的所有标签
print(res)
-拿出页面中所有图片
res = soup.find_all(src=True)
for item in res:
    url = item.attrs.get('href')
    print(url)

1.6 方法  标签名或属性名 = 方法
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')  # 只有..而没有..
print(soup.find_all(has_class_but_no_id))

1.7 
res = soup.find_all(name='a', limit=2)  # find的本质是find_all + limit=1
# body标签下的第一个没有id的p标签下的第一层找a标签
res = soup.body.find(name='p', id=False).find_all(name='a', recursive=False)
print(res)
'''
find:找第一个
find_all:找所有
'''

css选择器

1.只需要会了css选择,几乎所有的解析器[bs4,lxml...],都会支持css和xpath
1.1 标签名
1.2  .类名
1.3 #id号
1.4 body a   body下子子孙孙中得a
1.5 body>a  body下子的a,没有孙
1.6 其他的参照css选择器

2.例子
from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my p" class="title">asdfasdf<b id="bbb" class="boldest">The Dormouse's story</b>
</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
soup = BeautifulSoup(html_doc, 'lxml')
res = soup.select('a')  # 找所有的a
res = soup.select('#link1')  # 找id为link1
res = soup.select('.sister')  # 找类名的sister
res = soup.select('body>p>a')  # 找body下的p下的a

res = soup.select('body>p>a:nth-child(2)')  # body下的p下的第2个a
res = soup.select('body>p>a:nth-last-child(1)')  # body下的p下的倒数第1个a

# [attribute=value]
res = soup.select('a[href="http://example.com/tillie"]')  # 取href属性为..的a
print(res)

selenium

selenium基本使用

1.requests发送http请求获取数据,获取数据是xml使用bs4解析,解析出想要的数据
-requests不能执行js,所以使用requests获取回来的数据,跟直接在浏览器中看到的数据,可能不一样
-如果使用requets,需要分析当次请求发出了多少请求,每个都要发送一次,才能拼凑出网页完整的数据

2.selenium操作浏览器,控制浏览器,模拟人的行为
-selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题
-selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果,可支持多种浏览器

3.使用
3.1安装
-pip3 install selenium
-下载浏览器驱动:selenium操作浏览器,需要有浏览器(谷歌浏览器),谷歌浏览器驱动
https://registry.npmmirror.com/binary.html?path=chromedriver/
-浏览器版本对应的驱动 107.0.5304.122	找到相应的驱动

3.2使用代码测试
from selenium import webdriver
import time

# 驱动放到环境变量中,就不用传这个参数了
# 打开一个浏览器
bro = webdriver.Chrome(executable_path='./chromedriver.exe')
# 在地址栏输入网站
bro.get('http://www.baidu.com')
time.sleep(3)  # 3秒钟后
bro.close()  # 关闭tab页
bro.quit()  # 关闭浏览器

无界面浏览器

1.做爬虫时不希望有一个浏览器打开,谷歌支持无头浏览器,后台运行,没有浏览器的图形化(GUI)界面

2.使用
from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Options

# 实例化一个对象
chrome_options = Options()
# chrome_options.add_argument('window-size=1920x3000')  # 指定浏览器分辨率
# chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
# chrome_options.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
# chrome_options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
chrome_options.add_argument('--headless')  # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
# chrome_options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  # 手动指定使用的浏览器位置

bro = webdriver.Chrome(executable_path='./chromedriver.exe', options=chrome_options)
# 在地址栏输入网站
bro.get('https://www.jd.com/')
print(bro.page_source)  # 浏览器中看到的页面的内容
time.sleep(3)  # 3秒钟后
bro.close()  # 关闭tab页
bro.quit()  # 关闭浏览器

selenium其它用法

小案例,自动登录百度

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
# 在地址栏输入网站
bro.get('http://www.baidu.com/')
bro.implicitly_wait(10)  # 等待10秒钟,找一个标签
bro.maximize_window()  # 全屏
# 通过a标签文字内容查找标签
a = bro.find_element(by=By.LINK_TEXT, value='登录')
a.click()  # 点击标签

# 页面中id唯一,如果有id,优先用id
input_name = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__userName')
# 输入用户名
input_name.send_keys('[email protected]')  # 输入账号
time.sleep(1)

input_password = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__password')
input_password.send_keys('123')  # 输入密码
time.sleep(1)

input_submit = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__submit')
input_submit.click()  # 点击登录
time.sleep(5)

bro.close()  # 关闭tab页

获取位置属性大小,文本

bro.find_element(by=By.ID, value='id号')
bro.find_element(by=By.LINK_TEXT, value='a标签文本内容')
bro.find_element(by=By.PARTIAL_LINK_TEXT, value='a标签文本内容模糊匹配')
bro.find_element(by=By.CLASS_NAME, value='类名')
bro.find_element(by=By.TAG_NAME, value='标签名')
bro.find_element(by=By.NAME, value='属性name')
# -----通用的----
bro.find_element(by=By.CSS_SELECTOR, value='css选择器')
bro.find_element(by=By.XPATH, value='xpath选择器')
  • 12306登录二维码
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import base64

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
# 在地址栏输入网站
bro.get('https://kyfw.12306.cn/otn/resources/login.html')
bro.implicitly_wait(10)
bro.maximize_window()

a = bro.find_element(by=By.LINK_TEXT, value='扫码登录')
a.click()
code = bro.find_element(by=By.CSS_SELECTOR, value='#J-qrImg')

# 方案1:通过位置和大小将二维码截图
print(code.id)
print(code.location)
print(code.tag_name)
print(code.size)

# 方案2:通过src属性获取到图片
print(code.location)
print(code.size)
print(code.id)  # 不是标签的id号
print(code.tag_name)  # 是标签的名字
s = code.get_attribute('src')
print(s)
with open('code.png', 'wb') as f:
    res = base64.b64decode(s.split(',')[-1])
    f.write(res)

time.sleep(3)
bro.close()  # 关闭tab页

等待元素被加载

-代码执行的很快,有些标签还没加载出来,直接取,是取不到,要等待一下
-隐士等待
bro.implicitly_wait(10)  # find找标签的时候,如果找不到,等最多10s钟

元素操作

-点击
标签.click()
-input写文字
标签.send_keys('文字')
-input清空文字
标签.clear()

-模拟键盘操作
from selenium.webdriver.common.keys import Keys
input_search.send_keys(Keys.ENTER)  # 回车

执行js代码

from selenium import webdriver
import time

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
# 在地址栏输入网站
bro.get('https://www.jd.com/')

1.打印了cookie
bro.execute_script('alert(document.cookie)')

2.滚动页面,到最底部
2.1一点点向下滑动
for i in range(10):
    y = 400 * (i + 1)
    bro.execute_script(f'scrollTo(0,{y})')
    time.sleep(1)

2.2一次性直接滑动到最底部
bro.execute_script('scrollTo(0,document.body.scrollHeight)')

time.sleep(3)
bro.close()  # 关闭tab页

切换选项卡

from selenium import webdriver
import time

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
# 在地址栏输入网站
bro.get('https://www.jd.com/')

# 使用js打开新的选项卡
bro.execute_script('window.open()')  # 打开京东

# 切换到这个选项卡上,刚刚打开的是第一个
bro.switch_to.window(bro.window_handles[1])
bro.get('http://www.taobao.com')  # 打开淘宝
time.sleep(2)
bro.switch_to.window(bro.window_handles[0])  # 回到京东

time.sleep(3)
bro.close()  # 关闭tab页
bro.quit()  # 关闭浏览器

浏览器前进后退

from selenium import webdriver
import time

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
# 在地址栏输入网站
bro.get('https://www.jd.com/')  # 打开京东

time.sleep(2)
bro.get('https://www.taobao.com')  # 打开淘宝

time.sleep(2)
bro.get('https://www.bilibili.com/')  # 代开了B站

time.sleep(3)
bro.close()  # 关闭tab页
bro.quit()  # 关闭

异常处理

from selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameException
try:
except Exception as e:
    print(e)
finally:
    bro.close()

selenium登录cnblogs获取cookie

1.登录并获取cookies
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import json

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://www.cnblogs.com/')
bro.implicitly_wait(10)
try:
    # 找到登录按钮
    submit_btn = bro.find_element(By.LINK_TEXT, value='登录')
    submit_btn.click()
    time.sleep(1)
    username = bro.find_element(By.ID, value='mat-input-0')
    password = bro.find_element(By.ID, value='mat-input-1')
    username.send_keys("xxx")
    password.send_keys('123')
    submit = bro.find_element(By.CSS_SELECTOR,
                              value='body > app-root > app-sign-in-layout > div > div > app-sign-in > app-content-container > div > div > div > form > div > button')
    time.sleep(10)
    submit.click()
    # 会有验证码,滑动,手动操作完了,敲回车,程序继续往下走
    input()
    cookie = bro.get_cookies()
    print(cookie)
    with open('cnblogs.json', 'w', encoding='utf-8') as f:
        json.dump(cookie, f)
    time.sleep(5)
except Exception as e:
    print(e)
finally:
    bro.close()  # 关闭tab页

2.打开cnblose,自动写入cookie,我就是登录状态了
bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://www.cnblogs.com/')
bro.implicitly_wait(10)
time.sleep(3)
# 把本地的cookie写入,就登录了
with open('cnblogs.json', 'r', encoding='utf-8') as f:
    cookie = json.load(f)

for item in cookie:
    bro.add_cookie(item)

3.刷新一下页面
bro.refresh()
time.sleep(10)
bro.close()

抽屉半自动点赞

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import json
import requests

bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://dig.chouti.com/')
bro.implicitly_wait(10)
try:
    # 找到登录按钮
    submit = bro.find_element(By.ID, value='login_btn')
    # 有的页面button能找到,但是点击不了,报错,可以使用js点击它
    bro.execute_script("arguments[0].click()", submit)
    time.sleep(2)
    username = bro.find_element(by=By.NAME, value='phone')
    username.send_keys('18953675221')
    password = bro.find_element(by=By.NAME, value='password')
    password.send_keys('lqz123')
    time.sleep(3)
    submit_button = bro.find_element(By.CSS_SELECTOR,
                                     'body > div.login-dialog.dialog.animated2.scaleIn > div > div.login-footer > div:nth-child(4) > button')
    submit_button.click()

    # 验证
    input()
    cookie = bro.get_cookies()
    print(cookie)
    with open('chouti.json', 'w', encoding='utf-8')as f:
        json.dump(cookie, f)

    # 找出所有文章的id号
    div_list = bro.find_elements(By.CLASS_NAME, 'link-item')
    l = []
    for div in div_list:
        article_id = div.get_attribute('data-id')
        l.append(article_id)
except Exception as e:
    print(e)
finally:
    bro.close()  # 关闭tab页

with open('chouti.json', 'r', encoding='utf-8')as f:
    cookie = json.load(f)
# selenium的cookie不能直接给request用,需要有些处理
request_cookies = {}
for item in cookie:
    request_cookies[item['name']] = item['value']
print(request_cookies)
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}
for i in l:
    data = {'linkId': i}
res = requests.post('https://dig.chouti.com/link/vote', data=data, headers=headers, cookies=request_cookies)
print(res.text)

标签:res,time,selenium,bro,使用,import,find
From: https://www.cnblogs.com/riuqi/p/16926279.html

相关文章

  • selenium的基本使用
    selenium的基本使用bs4搜索文档树frombs4importBeautifulSouphtml_doc="""<html><head><title>TheDormouse'sstory</title></head><body><pid="myp"class......
  • 例程分析:GPIO输出——使用固件库点亮LED灯
     1 编程要点①使能GPIO端口时钟;②初始化GPIO目标引脚为推挽输出模式;③编写简单测试程序,控制GPIO引脚输出高、低电平。2 代码分析 宏定义的意义:通过把硬件相关......
  • Locust 压测介绍和使用
    背景:随着公司对项目质量越来越看重,性能测试已经慢慢日常化,不同之前性能测试在高峰之前做,所以需要一个可以随时对某些场景接口进行压测的实现方法。目前市场使用的压测工......
  • git bash使用笔记
    Gitbash使用笔记Version:Git1.6.11.gitclonesrc   克隆远程版本库。src为远程版本库的路径,默认地,Git会把src的最下一级目录名作为clone对象在本地的根目录。如,git......
  • gitee使用
    1、github的国内跳转github国内无法直接访问,所以直接使用gitee导入github工程https://gitee.com/  2、虚拟机配置ssh公钥https://gitee.com/profile/sshkeys ht......
  • 【vcpkg】使用vcpkg安装库
    https://blog.csdn.net/cjmqas/article/details/79282847使用vcpkg查看vcpkg支持的开源库列表执行命令.\vcpkg.exesearch安装一个开源库这里的“安装”其实是指下......
  • 使用docker部署nginx服务
    docker安装nginx1.查找镜像dockersearch命令查找,也可以去dockerhub(https://hub.docker.com)上搜索!!![root@localhost~]#dockersearchnginxNAME......
  • 一文学会使用Vue3
    一文学会使用Vue3本文适合Vue初学者,或者Vue2迁移者,当然还是建议Vue3官网完全过一遍。不适合精通原理,源码的大佬们。先推荐两个vscode插件Volar首先推荐Volar,使用vscode......
  • Quartz_简单编程式任务调度使用(SimpleTrigger)
    最近在工作中,要做定时任务的更能,最开始的时候,想到的是JavaSE中,自带Timer及TimerTask联合使用,完成定时任务。最后发现,随着业务的复杂,JDK中的Timer和TimerTask......
  • std::filesystem 使用时编译不过去
    #include<filesystem>namespacefs=std::filesystem;解决方法:https://stackoverflow.com/questions/53201991/how-to-use-stdfilesystem-on-gcc-8实际是需要在编译......