selenium,selenium基本使用,使用selenium模拟登入百度,selenium方法,无界面浏览器,selenium的其他用法,selenium登录cnblogs获取cookie,requests中使用selenium的cookie

selenium

selenium模块:模拟操作浏览器,完成人的行为
'''
    selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题
'''

selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果,可支持多种浏览器

'''
	安装:pip install selenium
'''

下载对应版本的浏览器驱动,推荐谷歌
	https://registry.npmmirror.com/binary.html?path=chromedriver/
    
    '''
    	下载好后放在项目根目录下
    '''

selenium基本使用

from selenium import webdriver

# 相当于双击谷歌浏览器,打开浏览器
1.bro=webdriver.Chrome(executable_path='./chromedriver.exe')
'''
# bro=webdriver.Chrome() # 不写路径,要放到项目路径或环境变量中
'''

# 相当于在地址栏中输入地址
2.bro.get('http://www.baidu.com')

# 关闭浏览器
3.bro.close()  # 关闭标签,如果只有一个标签那就是关闭浏览器,如果有多个标签则关闭当前的标签
bro.quit()   # 关闭浏览器,正儿八经的关闭浏览器

使用selenium模拟登入百度

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

1.打开浏览器,访问百度
	bro = webdriver.Chrome()
	bro.implicitly_wait(10) # 隐式等待,无论页面中哪个标签找不到,会最多等待10秒
    bro.get('http://www.baidu.com/')

2.根据标签id,获取登入标签,并点击
	#btn = bro.find_element_by_id('s-top-loginbtn') # 老版本
	btn = bro.find_element(by=By.ID,value='s-top-loginbtn') # 新版本
    '''
	(2)根据文字找标签:a标签的文字
    btn = bro.find_element(by=By.LINK_TEXT,calue='登录')
    '''
    # 点击登入按钮,弹出登入框
    btn.click()

3.获取用户名和密码输入框,并输入用户名和密码
	username = bro.find_element(by=By.ID,value='TANGRAM__PSP_11__userName')
	password = bro.find_element(by=By.ID,value='TANGRAM__PSP_11__password')
	# 写入文字
    username.send_keys('1577540324@qq.com')
    password.send_keys('11111')
    
    # 获取登入按钮,并点击
   	btn_login=bro.find_element(by=By.ID,value='TANGRAM__PSP_11__submit')
    btn_login.click()
    
    '''
    	后续可能需要验证码,这个需要手动解决,虽然有框架能解决验证码,但是复杂的验证码还得是靠人
    '''

selenium方法

from selenium.webdriver.common.by import By
from selenium import webdriver
bro = webdriver.Chrome()


(1)查找标签,获取标签对象 find_element 和 find_elements 
    1.bro.find_element(by=By.ID,value='标签id') # 根据id
    2.bro.find_element(by=By.link_text,value='a标签的文字') # 根据a标签的文字
    3.bro.find_element(by=By.partial_link_text,value='a标签的文字') # 根据a标签的文字模糊匹配
    4.bro.find_element(by=By.tag_name,value='标签名') # 根据标签名
    5.bro.find_element(by=By.class_name,value='class名') # 根据类名
    6.bro.find_element(by=By.name ,value='name属性值') # 根据name属性
    7.bro.find_element(by=By.css_selector ,value='css选择') # css选择器
    8.bro.find_element(by=By.xpath ,value='') # xpath


(2)点击某个按钮
    标签对象.click()


(3) 向输入框中输入内容
    标签对象.send_keys('内容')
    
(4) 获取属性值
	标签对象.get_attribute('属性名')

无界面浏览器

'''
	不显示的打开浏览器的图形化界面,还能获取数据
'''
import time

from selenium import webdriver
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下如果系统不支持可视化不加这条会启动失败

driver=webdriver.Chrome(options=chrome_options)
driver.get('https://www.cnblogs.com/')
print(driver.page_source)  # 当前页面的内容(html内容)
time.sleep(2)
driver.close()

selenium的其他用法

获取二维码

import time
import base64
from selenium import webdriver
from selenium.webdriver.common.by import By
bro=webdriver.Chrome()
btn=bro.find_element(By.LINK_TEXT,'扫码登录')
btn.click()
img=bro.find_element(By.ID,'J-qrImg')

print(img.location) # 坐标,(x,y) 原点在左上角
print(img.size) # 图片的大小
print(img.id)  # 不是标签的id号
print(img.tag_name)  # 是标签的名字 img
print(img.get_attribute('src')) # 获取img标签的src属性值
'''
	在src中是一些base64编码后的数据
'''
s=img.get_attribute('src')
with open('code.png','wb') as f:
     res=base64.b64decode(s.split(',')[-1])
     f.write(res)
bro.close()

等待元素被加载

程序操作页面非常快,所以在取每个标签的时候,标签可能没有加载号,需要设置等待
	-显示等待:不需要了解
    -隐士等待:bro.implicitly_wait(10)

标签操作(其他)

1.清空
	标签对象.clear()
    
2.滑动屏幕到最底部(滑动加载)
	bro.execute_script('scrollTo(0,document.body.scrollHeight)')

执行js代码

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
bro=webdriver.Chrome()
bro.get('https://www.pearvideo.com/category_8')
bro.execute_script('alert(md5_vm_test)')

'''
bro.execute_script('js代码')

执行js用途:1 普通滑屏,打开新标签   2 可以执行js代码,别人网站的变量,函数,都可以拿到并执行的
'''

切换页面

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
bro=webdriver.Chrome()


bro.get('https://www.pearvideo.com/category_8')

# 打开新的选项卡(打开新的页面)
bro.execute_script('window.open()')
# bro.switch_to_window(bro.window_handles[1])  # 老版本,弃用了
bro.switch_to.window(bro.window_handles[1])
bro.get('http://www.baidu.com')

time.sleep(2)
bro.switch_to.window(bro.window_handles[0])
time.sleep(2)
# bro.close()
bro.quit()

浏览器前进后退

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
bro=webdriver.Chrome()


bro.get('https://www.pearvideo.com/category_8')
time.sleep(1)
bro.get('https://www.baidu.com')

bro.back() # 后退

time.sleep(1)
bro.forward() # 前进


bro.quit()

异常处理

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException,NoSuchElementException,NoSuchFrameException
bro=webdriver.Chrome()

try:
    bro.get('https://www.pearvideo.com/category_8')
    time.sleep(1)
    bro.get('https://www.baidu.com')

    bro.back() # 后退
    raise Exception('报错了')
    time.sleep(1)
    bro.forward()
except Exception as e:
    print(e)
finally:
    bro.quit()

selenium登录cnblogs获取cookie

import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
bro=webdriver.Chrome()
bro.implicitly_wait(10)


####1  登录成功
# try:
#     bro.get('https://www.cnblogs.com/')
#     time.sleep(1)
#     btn=bro.find_element(By.LINK_TEXT,'登录')
#     btn.click()
#     time.sleep(3)
#     username=bro.find_element(By.ID,'mat-input-0')
#     password=bro.find_element(By.ID,'mat-input-1')
#     username.send_keys('616564099@qq.com')
#     time.sleep(1)
#     password.send_keys('lqz')
#
#     btn_login=bro.find_element(By.CSS_SELECTOR,'body > app-root > app-sign-in-layout > div > div > app-sign-in > app-content-container > div > div > div > form > div > button')
#     btn_login.click()
#     # time.sleep(20) # 人工破解验证码,登录成功
#     input()
#     cookies=bro.get_cookies()
#     print(cookies)
#     with open('cnblgos.json','w',encoding='utf-8') as f:
#         json.dump(cookies,f)
#
#     time.sleep(2)
#
# except Exception as e:
#     print(e)
#
# finally:
#     bro.quit()


### 2 打开页面
try:
    bro.get('https://www.cnblogs.com/')
    time.sleep(2)
    # 把cookie写入浏览器,刷新一下,就登录了
    with open('cnblgos.json','r',encoding='utf-8') as f:
        res=json.load(f)
    for item in res:
        bro.add_cookie(item)

    # 刷新浏览器
    bro.refresh()
    time.sleep(2)

except Exception as e:
    print(e)

finally:
    bro.quit()

requests中使用selenium的cookie

selenium的cookie格式为:
    [
        {
            'name':....,
            'value':....,
        },
        {
            'name':....,
            'value':....,
        },
        {
            'name':....,
            'value':....,
        },
    ]
每一个字典中都有name 和value的键值对
我们只需要把这些值拿出来给request cookie即可
res = requests.get('',cookie={name:value,name:value})
posted @ 2022-08-02 15:56  春游去动物园  阅读(125)  评论(0编辑  收藏  举报