爬虫篇:selinium的使用

一、 selenium基本使用

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
# 由于requests不能执行js,有的页面内容,我们在浏览器中可以看到,但是请求下来没有---》selenium模块:模拟操作浏览器,完成人的行为 # selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题 # selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果,可支持多种浏览器 # 安装 pip3.8 install selenium # 使用 -由于是驱动浏览器:需要确定好驱动哪个浏览器(ie,火狐,谷歌(推荐)) -下载相应的驱动

环境准备

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
# 驱动谷歌浏览器----》下载谷歌驱动---》谷歌官网访问不到---》访问淘宝镜像站下载: https://registry.npmmirror.com/binary.html?path=chromedriver/ 注意: # (1)浏览器版本要和驱动对应好 103.0.5060.134 # (2)放到项目路径下或者环境变量中 # 遇到的问题 """ selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary """ 问题产生的可能原因:为了版本对应直接下载了安装包,然后环境就乱了; 如果遇到类似的问题,可以采用以下方式解决,加上下面两行代码,其他都正常操作: ------------------------------------ option = webdriver.ChromeOptions() option.binary_location=r'chrome的绝对路径' ------------------------------------ bro = webdriver.Chrome() bro.get('https://www.baidu.com')

打开和关闭浏览器

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
from selenium import webdriver import time # 第一步: 等同于你双击谷歌浏览器,打开了浏览器 # bro=webdriver.Chrome(executable_path='./chromedriver.exe') bro=webdriver.Chrome() # 不写路径,要放到项目路径或环境变量中 # 第二步:在地址栏输入地址 bro.get('http://www.baidu.com') time.sleep(2) # 第三步:关闭浏览器 bro.close() # 关闭标签 bro.quit() # 关闭浏览器

模拟登录百度

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
##### 模拟登录百度 ##### 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) # 3 点击一下按钮 btn.click() # 4 用户名,密码输入框 username = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__userName') password = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__password') # 5 输入账号密码 username.send_keys('616564099@qq.com') time.sleep(1) password.send_keys('lqz123') # 6 点击登录按钮 btn_login=bro.find_element(by=By.ID,value='TANGRAM__PSP_11__submit') btn_login.click() # time.sleep(8) bro.close() # 关闭标签

打开百度,搜索美女

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
# 打开百度,搜索美女 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()

小结

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
# 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.implicitly_wait(10) 隐士等待,最多等待10

二、 无界面浏览器

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
# 不显示的打开浏览器的图形化界面,还能获取数据 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其它用法

3.1 获取位置属性大小,文本

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
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') # 获取src属性 with open('code.png','wb') as f: res=base64.b64decode(s.split(',')[-1]) f.write(res) bro.close()

3.2 等待元素被加载

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

3.3 元素操作

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
# 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 新版本: 元素=bro.find_element(By.标签类型,value) # img=bro.find_element(By.ID,'J-qrImg') # 2 点击 标签.click() # 3 写入文字 标签.send_keys() # 4 清空 标签.clear() # 5 滑动屏幕到最底部(滑动加载) bro.execute_script('scrollTo(0,document.body.scrollHeight)')

3.4 执行js代码

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
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.execute_script()括号里面写js代码 bro.execute_script('scrollTo(0,document.body.scrollHeight)') bro.execute_script('alert(md5_vm_test)') bro.execute_script('alert(md5_vm_test())') bro.execute_script('arguments[0].click()', login_btn) # 使用js点击某个按钮 time.sleep(1) bro.close() # 执行js用途:1 普通滑屏,打开新标签 2 可以执行js代码,别人网站的变量,函数,都可以拿到并执行的

3.5 切换选项卡

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
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()') # 切换到另一个选项卡,数字1代表选项卡索引 # 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) # 切换回原来的选项卡,数字0代表选项卡索引 bro.switch_to.window(bro.window_handles[0]) time.sleep(2) # bro.close() bro.quit()

3.6 浏览器前进后退

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
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()

3.7 异常处理

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
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

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
import time import json from selenium import webdriver from selenium.webdriver.common.by import By bro=webdriver.Chrome() bro.implicitly_wait(10) # 1 登录成功并获取cookies写入文件 try: bro.get('https://www.cnblogs.com/') time.sleep(1) # 1)点击登录标签进入输入框 btn=bro.find_element(By.LINK_TEXT,'登录') btn.click() time.sleep(3) # 2)输入用户名密码 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') # 3)找到登录按钮并点击 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() # 手动阻塞 # 4)获取cookies,json格式 ---------------------------------------------------------- cookies=bro.get_cookies() ---------------------------------------------------------- # 5)存入cnblgos.json 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 打开页面,添加文件中的cookies到浏览器 try: bro.get('https://www.cnblogs.com/') time.sleep(2) # 1)把cookie写入浏览器,刷新一下,就登录了 with open('cnblgos.json','r',encoding='utf-8') as f: res=json.load(f) # 2)循环添加文件中的cookies到浏览器 ---------------------------------------------------------- for item in res: bro.add_cookie(item) ---------------------------------------------------------- # 3)刷新浏览器 bro.refresh() time.sleep(2) except Exception as e: print(e) finally: bro.quit()

五、 抽屉半自动点赞+评论

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
# 注意:selenium的cookie和requests用的cookie格式不太一样 [{},{}]--->{'key':'value'} name,value--->{name:value,name:value} # 使用cookies进行登录然后进入文章进行点赞 from selenium import webdriver from selenium.webdriver.common.by import By import time import json # 一、使用requests模块, 发送点赞请求 import requests bro = webdriver.Chrome() bro.get('https://dig.chouti.com/') bro.implicitly_wait(10) # bro.maximize_window() # 全屏 try: # 1 取出当前页面中所有的文章id,并添加到ids列表中 ids = [] id_list = bro.find_elements(By.CSS_SELECTOR, 'div.link-item') for item in id_list: ids.append(item.get_attribute('data-id')) print(ids) -------------------------------------------------------- # 2 点击登录按钮,并输入账号密码,再点击登录 # login_btn=bro.find_element(By.CSS_SELECTOR,'#login_btn') login_btn = bro.find_element(By.ID, 'login_btn') bro.execute_script('arguments[0].click()', login_btn) # 使用js点击 # login_btn.click() time.sleep(1) username = bro.find_element(By.CSS_SELECTOR, 'body > div.login-dialog.dialog.animated2.scaleIn > div > div.login-body > div.form-item.login-item.clearfix.phone-item.mt24 > div.input-item.input-item-short.left.clearfix > input') password = bro.find_element(By.CSS_SELECTOR, 'body > div.login-dialog.dialog.animated2.scaleIn > div > div.login-footer > div.form-item.login-item.clearfix.mt24 > div > input.input.pwd-input.pwd-input-active.pwd-password-input') username.send_keys('18953675221') password.send_keys('lqz123') time.sleep(3) login_btn2 = bro.find_element(By.CSS_SELECTOR, 'body > div.login-dialog.dialog.animated2.scaleIn > div > div.login-footer > div:nth-child(4) > button') login_btn2.click() input('人工操作') -------------------------------------------------------- # 3 获取cookie并存储到当前路径下的chouti.json with open('chouti.json', 'w', encoding='utf-8') as f: json.dump(bro.get_cookies(), f) time.sleep(2) -------------------------------------------------------- # 4 使用requests点赞,匹配请求头 header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36' } -------------------------------------------------------- # 5 使用request添加cookie的方式,封装好放到请求中去 with open('chouti.json', 'r', encoding='utf-8') as f: cookie = {} cookie_list = json.load(f) for item in cookie_list: cookie[item['name']] = item['value'] # {Hm_lpvt_03b2668f8e8699e91d479d62bc7630f1:zqZgG2gcELxAevskCyAiB9m0YdTMFfrEHyHpqnH3uLyQBGCj38e8ZNNkVM4nXDmhKuCfjjQHcX8iCRefrMuAdxV8eSUR%2FmwUXMCcn9BtIMlfGLlENdR1QsrFzFZhLo2GREw%3D,} print(cookie) -------------------------------------------------------- # 6 将获取到的文章id也添加到请求的data中去 for item in ids: res = requests.post('https://dig.chouti.com/link/vote', headers=header, data={ 'linkId': item }, cookies=cookie) print(res.text) # 请求的结果 except Exception as e: print(e) finally: bro.close() ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- # 二、评论功能 # 1 匹配请求头User-Agent、Referer header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36', 'Referer': 'https://dig.chouti.com/', } -------------------------------------------------------- # 2 获取cookie with open('chouti.json', 'r', encoding='utf-8') as f: cookie = {} cookie_list = json.load(f) for item in cookie_list: cookie[item['name']] = item['value'] # {Hm_lpvt_03b2668f8e8699e91d479d62bc7630f1:zqZgG2gcELxAevskCyAiB9m0YdTMFfrEHyHpqnH3uLyQBGCj38e8ZNNkVM4nXDmhKuCfjjQHcX8iCRefrMuAdxV8eSUR%2FmwUXMCcn9BtIMlfGLlENdR1QsrFzFZhLo2GREw%3D,} print(cookie) -------------------------------------------------------- # 3 发送请求,携带所需参数 res = requests.post('https://dig.chouti.com/comments/create', headers=header, cookies=cookie, data={ 'content': '写的真不好搞好', 'linkId': '35860995', 'parentId': 0, 'pictureUrl': '', 'subjectId': 4, }) print(res.text)

六、 动作链(了解)

复制代码
  • 1
# 模拟按住鼠标拖动的效果,或者是在某个标签上的某个位置点击的效果,主要用来做验证码的破解(滑动验证码)
复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
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: # 1 切换到iframeResult窗口中,再获取需要操作的两个标签 driver.switch_to.frame('iframeResult') ##切换到iframeResult sourse=driver.find_element(By.ID,'draggable') target=driver.find_element(By.ID,'droppable') -------------------------------------------------------- # 2 执行动作链 # 方式一:基于同一个动作链串行执行 # 拿到动作链对象,并把动作放到动作链中,准备串行执行 (写法1) actions=ActionChains(driver) # 拿到动作链对象 actions.drag_and_drop(sourse,target) # 把动作放到动作链中,准备串行执行 actions.perform() (写法2) 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轴的距离 # 一次只移动2个单位 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() # 总结:1)方式一:目标source移动到目标target的位置 -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) 原来的12306的点选,cnblgs选出所有红绿灯的验证码 (2)方式二:指定sourse移动的距离(xoffset) -ActionChains(driver).click_and_hold(sourse).perform() # 按住 -ActionChains(driver).move_by_offset(xoffset=2,yoffset=0).perform() # 移动 ActionChains(driver).release().perform() # 放下 # 12306 自动登录---》滑块显示不出来---》检测到咱们使用自动化测试软件控制了

案例:登录12306

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
import time from selenium.webdriver.common.by import By from selenium.webdriver import ActionChains from selenium import webdriver # 匹配chrome浏览器 option = webdriver.ChromeOptions() option.binary_location=r'D:\我的下载\chrome' # 1 打开浏览器,和超级鹰登录界面 bro = webdriver.Chrome() bro.get('https://kyfw.12306.cn/otn/resources/login.html') bro.maximize_window() try: # 2 输入账号密码 username = bro.find_element(By.ID,'J-userName') password = bro.find_element(By.ID,'J-password') username.send_keys('1098257879@qq.com') password.send_keys('mtljq1098257879') login_btn = bro.find_element(By.ID,'J-login') # 3 点击登录,然后进入滑块验证码识别 login_btn.click() time.sleep(3) # 4 解决特征识别(12306会对浏览器特征进行识别,不允许自动化登录,使用以下两句话解决 script = 'Object.defineProperty(navigator, "webdriver", {get: () => false,});' bro.execute_script(script) # 5 使用动作链,然后开始滑动 huakuai = bro.find_element(By.XPATH,'//*[@id="nc_1_n1z"]') ActionChains(bro).click_and_hold(huakuai).perform() # 按住 time.sleep(3) n = 1 while n <= 6: ActionChains(bro).move_by_offset(xoffset=50, yoffset=0).perform() # 移动 time.sleep(1) n += 1 ActionChains(bro).release().perform() # 松开 time.sleep(10) except Exception as e: print(e) finally: bro.close()

七、 打码平台使用

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
# 验证码的破解 -简单的数字字母组合可以使用图像识别(python 现成模块),成功率不高 -使用第三方打码平台(破解验证码平台),花钱,把验证码图片给它,它给你识别完,返回给你 # 云打码,超级鹰 306334678 lqz123 """超级鹰使用步骤""" # 1 注册登录超级鹰账号 http://www.chaojiying.com/user/login/ # 2 下载python的超级鹰模块包 http://www.chaojiying.com/api-14.html # 3 将chaojiying.py文件放到项目目录下 chaojiying.py # 4 在需要的文件中进行导入并使用 from chaojiying import Chaojiying_Client chaojiying = Chaojiying_Client(超级鹰账号, 超级鹰密码, 软件ID号) im = open('small_code.png', 'rb').read() # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要// print(chaojiying.PostPic(im, 1902)) # 打印结果 chaoji_code = chaojiying.PostPic(im, 1902).get('pic_str') # 获取结果中产出的验证码

案例:使用超级鹰模块登录超级鹰

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
import time from selenium.webdriver.common.by import By from selenium import webdriver from PIL import Image # 匹配chrome浏览器 option = webdriver.ChromeOptions() option.binary_location=r'D:\我的下载\chrome' # 打开浏览器,和超级鹰登录界面 bro = webdriver.Chrome() bro.get('http://www.chaojiying.com/user/login/') bro.maximize_window() ##### 注意:如果截图不准需要手动调整分辨率,加上下面代码,对应电脑分辨率125%为例 ##### bro.execute_script('document.body.style.zoom="0.8"') time.sleep(3) try: # 1 保存整个页面截图 bro.save_screenshot('code.png') # 2 使用Xpath获取到验证码的标签 img_s = bro.find_element(By.XPATH,'/html/body/div[3]/div/div[3]/div[1]/form/div/img') # 3 获取标签的位置 location = img_s.location # 4 获取标签的大小size size = img_s.size # 5 使用pillow抠出大图中的验证码小图 # 5.1 计算验证码的位置 img_tu = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height'])) # 5.2 打开截图 img_b = Image.open('./code.png') # 5.3 抠出小图 fram = img_b.crop(img_tu) # 5.4 保存小图 fram.save('small_code.png') # 6 使用超级鹰进行打码 from chaojiying import Chaojiying_Client chaojiying = Chaojiying_Client('1831853664', 'st0916..', '937252') im = open('small_code.png', 'rb').read() # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要// print(chaojiying.PostPic(im, 1902)) # 打印识别后的结果,字典形式,里面的pic_str对应的就是验证码的结果 except Exception as e: print(e) finally: bro.close()

几个爬虫案例

复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
# 1 爬红楼梦小说 #http://www.shicimingju.com/book/hongloumeng.html import requests from bs4 import BeautifulSoup ret=requests.get('https://www.shicimingju.com/book/hongloumeng.html') ret.encoding='utf-8' soup=BeautifulSoup(ret.text,'lxml') li_list=soup.find(class_='book-mulu').find('ul').find_all('li') with open('hlm.txt','w',encoding='utf-8') as f: for li in li_list: content=li.find('a').text url='https://www.shicimingju.com'+li.find('a').get('href') f.write(content) f.write('\n') res_content=requests.get(url) res_content.encoding = 'utf-8' res_content.encoding=res_content.apparent_encoding soup2=BeautifulSoup(res_content.text,'lxml') content_detail=soup2.find(class_='chapter_content').text f.write(content_detail) f.write('\n') print(content,'写入了') # 2 爬肯德基门店 # http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword import requests header = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36' } data = { 'cname': '', 'pid': 20, 'keyword': '浦东', 'pageIndex': 1, 'pageSize': 10 } ret = requests.post('http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword', data=data, headers=header) print(ret.json())
posted @   马氵寿  阅读(300)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
展开