Loading

selenium基本使用、无界面浏览器、selenium其它用法、selenium登录cnblogs获取cookie、动作链

selenium基本使用

# 由于requests不能执行js,有的页面内容,我们在浏览器中可以看到,但是请求下来没有---》selenium模块:模拟操作浏览器,完成人的行为
# selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题

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

# 安装
pip3.8 install selenium
# 使用
	-由于是驱动浏览器:需要确定好驱动哪个浏览器(ie,火狐,谷歌(推荐))
    -下载相应的驱动
# 1 基本使用
from selenium import webdriver
import time
# # 驱动谷歌浏览器----》下载谷歌驱动---》谷歌官网访问不到---》访问淘宝镜像站下载:https://registry.npmmirror.com/binary.html?path=chromedriver/
# # ###### 浏览器版本要和驱动对应好  103.0.5060.134
# # 放到项目路径下
#
# #第一步: 等同于你双击谷歌浏览器,打开了浏览器
# # bro=webdriver.Chrome(executable_path='./chromedriver.exe')
# bro=webdriver.Chrome() # 不写路径,要放到项目路径或环境变量中
# # 第二步:在地址栏输入地址
# bro.get('http://www.baidu.com')
#
# time.sleep(2)
# # 第三步:关闭浏览器
# bro.close()  # 关闭标签
#
# # bro.quit()  # 关闭浏览器


# 2 模拟登录百度
from selenium.webdriver.common.by import By

# bro = webdriver.Chrome()
# bro.implicitly_wait(10)  # 隐士等待,无论找页面中那个标签,如果找不到,会等待最多10s钟
# bro.get('https://www.baidu.com/')
# # 1 根据标签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, value='登录')
# print(btn)
#
# # 点击一下按钮
# btn.click()
# # 用户名,密码输入框
# 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('616564099@qq.com')
# time.sleep(1)
# password.send_keys('lqz123')
#
# btn_login=bro.find_element(by=By.ID,value='TANGRAM__PSP_11__submit')
# btn_login.click()
# time.sleep(8)
#
#
# bro.close()  # 关闭标签



#1  查找控件:bro.find_element(by=By.ID,value='TANGRAM__PSP_11__submit')
# 1、find_element_by_id   # 根据id
# 2、find_element_by_link_text # 根据a标签的文字
# 3、find_element_by_partial_link_text # 根据a标签的文字模糊匹配
# 4、find_element_by_tag_name    # 根据标签名
# 5、find_element_by_class_name  # 根据类名
# 6、find_element_by_name        # 根据name属性

# 7、find_element_by_css_selector  # css选择器
# 8、find_element_by_xpath         # xpath

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

# 3 向输入框中写内容
# 标签对象.send_keys(内容)




# 打开百度,搜索美女


bro=webdriver.Chrome()
bro.implicitly_wait(10)
bro.get('https://www.baidu.com/')
input_a=bro.find_element(By.NAME,value='wd')
input_a.send_keys('美女')
btn=bro.find_element(By.ID,'su')
time.sleep(1)
btn.click()

time.sleep(3)
bro.close()

无界面浏览器

# 不显示的打开浏览器的图形化界面,还能获取数据
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()
# bro.get('https://kyfw.12306.cn/otn/resources/login.html')
# bro.implicitly_wait(10)
# btn=bro.find_element(By.LINK_TEXT,'扫码登录')
#
# btn.click()
# time.sleep(1)
# img=bro.find_element(By.ID,'J-qrImg')
# print(img.location)
# print(img.size)
# print(img.id)  # 不是标签的id号
# print(img.tag_name)  # 是标签的名字
# # print(img.get_attribute('src'))
# 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 搜索标签:find_element:找第一个      find_elements:找所有
    # 1、find_element_by_id   # 根据id
    # 2、find_element_by_link_text # 根据a标签的文字
    # 3、find_element_by_partial_link_text # 根据a标签的文字模糊匹配
    # 4、find_element_by_tag_name    # 根据标签名
    # 5、find_element_by_class_name  # 根据类名
    # 6、find_element_by_name        # 根据name属性
    # 7、find_element_by_css_selector  # css选择器
    # 8、find_element_by_xpath         # xpath

# 2 点击
    标签.click()
# 3 写入文字
	标签.send_keys()
# 4 清空
	标签.clear()
    
    
# 5 滑动屏幕到最底部(滑动加载)
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')
time.sleep(1)
# 这里面写js代码
# bro.execute_script('scrollTo(0,document.body.scrollHeight)')
# bro.execute_script('alert(md5_vm_test)')
bro.execute_script('alert(md5_vm_test())')


time.sleep(1)
bro.close()

# 执行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()

动作链(了解)

# 模拟按住鼠标拖动的效果,或者是在某个标签上的某个位置点击的效果,主要用来做验证码的破解(滑动验证码)
from selenium import webdriver
from selenium.webdriver import ActionChains
import time
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable')
driver.implicitly_wait(10)  # 使用隐式等待

driver.maximize_window()

try:
    driver.switch_to.frame('iframeResult') ##切换到iframeResult
    sourse=driver.find_element(By.ID,'draggable')
    target=driver.find_element(By.ID,'droppable')


    #方式一:基于同一个动作链串行执行
    # actions=ActionChains(driver) #拿到动作链对象
    # actions.drag_and_drop(sourse,target) #把动作放到动作链中,准备串行执行

    actions=ActionChains(driver).click_and_hold(sourse)
    actions.drag_and_drop_by_offset(target,10,20)
    actions.perform()
    #方式二:不同的动作链,每次移动的位移都不同

    # ActionChains(driver).click_and_hold(sourse).perform()
    # distance = target.location['x'] - sourse.location['x']  # 两个控件的x轴的距离
    # track=0
    # while track < distance:
    #     ActionChains(driver).move_by_offset(xoffset=2,yoffset=0).perform()
    #     track+=2
    # # ActionChains(driver).move_by_offset(xoffset=distance, yoffset=0).perform()
    # ActionChains(driver).release().perform()

    time.sleep(10)


finally:
    driver.close()



总结

'''
    -ActionChains(driver).move_by_offset(xoffset=2,yoffset=0).perform()  滑块,滑动验证码的破解
    -actions.drag_and_drop_by_offset(target,10,20)  原来的12306的点选,cnblgs选出所有红绿灯的验证码
         actions=ActionChains(driver)
         actions.drag_and_drop_by_offset(target,10,20)
'''

检测到使用自动化测试软件的解决办法

# eg:12306 自动登录---》滑块显示不出来---》
解决办法:
	方式一:
    	# 解决特征识别
    script = 'Object.defineProperty(navigator, "webdriver", {get: () => false,});'
    bro.execute_script(script)
    方式二:
    	# 去除浏览器识别
		'''
		浏览器上方有“Chrome正受到自动测试软件的控制”,其实这个是可以去除的,实例化浏览器对象时加多一个参数就可以了
		'''
        option = ChromeOptions()
        option.add_experimental_option('excludeSwitches', ['enable-automation'])
        option.add_experimental_option("detach", True)

自动登录12306实例

import time

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

bro = webdriver.Chrome()
bro.maximize_window()


try:
    bro.get('https://kyfw.12306.cn/otn/resources/login.html')
    username = bro.find_element(By.ID, 'J-userName')
    password = bro.find_element(By.ID, 'J-password')
    username.send_keys('15249783301')
    password.send_keys('Zhengkaijian990722')
    login_btn = bro.find_element(By.ID, 'J-login')
    login_btn.click()
    # sliding_btn = bro.find_element(By.ID, 'nc_1_n1z')
    # bro.switch_to.frame('iframeResult') ##切换到iframeResult
    # input()
    time.sleep(3)
    # '/html/body/div[1]/div[4]/div[2]/div[2]/div/div/div[2]/div/div[1]/span'
    sourse = bro.find_element(By.XPATH, '/html/body/div[1]/div[4]/div[2]/div[2]/div/div/div[2]/div/div[1]/span')
    track = 0
    # 解决特征识别
    script = 'Object.defineProperty(navigator, "webdriver", {get: () => false,});'
    bro.execute_script(script)
    ActionChains(bro).click_and_hold(sourse).perform()
    while track <= 294:
        ActionChains(bro).move_by_offset(xoffset=50, yoffset=0).perform()
        track += 49
    ActionChains(bro).release().perform()
except Exception as e:
    print(e)
finally:
    time.sleep(3)
    bro.close()

posted @ 2022-08-03 18:56  香菜根  阅读(261)  评论(0编辑  收藏  举报