セレンのさまざまな使用法、およびシミュレートされた12306ログイン

  • セレンとクローラーの関係は何ですか?
    -Webサイトに動的にロードされたデータへの便利なアクセス-
    便利なシミュレートされたログイン
  • セレンとは何ですか?
    • ブラウザベースの自動化モジュール
  • セレン使用プロセス:
    • セレンをインストールする

    • ブラウザインストールドライバ(例:Google)をダウンロードする

      • ダウンロードパス:http://chromedriver.storage.googleapis.com/index.html
      • ドライバーとブラウザー間のマッピング関係:http://blog.csdn.net/huilan_same/article/details/51896672
      • ブラウザの自動化に基づいて操作コードを記述し
        ます。BaiduでLufeiXuechengと入力すると、それを見つけることができます。
    • Seleniumはiframe(スコープ)を処理します

      • ポジショニングタグがiframeタグに存在する場合は、bro.switch_to.iframe(id)を使用する必要があります
      • アクションチェーン(ドラッグ):selenium.webdriverからimport ActionChins
        • オブジェクトをインスタンス化します:ActionChins(bro)
        • click_and_hold(div):長押ししてクリック操作
        • move_by_offset(x、y)
        • perform()動的チェーンをすぐに実行します
        • action.release()アクションチェーンオブジェクトを解放します
    • 12306シミュレートされた着陸-
      スーパーイーグル(前回の記事で紹介したので、あまり説明しません)

      • 使用プロセスの公式ウェブサイト:http://www.chaojiying.com/about.html
        • 登録済み
        • ログインする
          • 質問ポイントクエリリチャージ
          • ソフトウェアの作成(id)
          • 開発ドキュメントダウンロードサンプルコード
    • 12306シミュレーションログインコーディングプロセス

      • セレンを使用してランディングページを開く
      • セレンによって現在開かれているページのスクリーンショットを撮る
      • 現在の写真のローカルエリア、確認コードエリアをトリミングします
        • 利点:検証コードの画像とシミュレートされたログインの間の1対1の対応
      • 検証コードの認識にスーパーイーグルを使用します(関連する座標に戻ります)
      • 関連する座標をクリックします
      • 動作確認コード画像関連コード
        まず、senleium基本使用コードを入れます。
from selenium import  webdriver
from lxml import etree
from time import sleep
#实例化浏览器兑现,传入浏览器的驱动程序
bro = webdriver.Chrome(executable_path='./chromedriver')
#让浏览器发起一个指定url对应请求
bro.get('http://125.35.6.84:81/xk/')
page_text = bro.page_source

#解析企业名称
tree = etree.HTML(page_text)
li_list = tree.xpath('//ul[@id="gzlist"]/li')
for li in li_list:
    name = li.xpath('./dl/@title')[0]
    print(name)
sleep(5)
bro.quit()

コード実行結果のいくつかの写真:
ここに写真の説明を挿入
BaiduにあるSenleiumの自動操作を見てみましょう。

from selenium import webdriver
from time import sleep
#设置驱动程序
bro = webdriver.Chrome('./chromedriver')
bro.get('http://taobao.com/')
#标签定位
serach_input = bro.find_element_by_id('q')
#标签交互
serach_input.send_keys('Ipone')
#执行一组js程序
bro.execute_script('window.scrollTo(0,document.body.scrollHeight)')
sleep(3)
#点击按钮
btn = bro.find_element_by_class_name('btn-search')
btn.click()

bro.get('http://www.baidu.com/')
bro.back()
sleep(2)
bro.forward()
sleep(2)
bro.quit()

自分で実行して効果を確認できます。結果は再生しません。
次はQQログインをシミュレートするコードです。もちろん、QQは入れません。最終結果は間違いなくログイン失敗です。独自のQQとパスワードを入力して、テストすることができます。

from selenium import webdriver
from time import sleep
#设置驱动程序
bro = webdriver.Chrome('./chromedriver')
bro.get('http://taobao.com/')
#标签定位
serach_input = bro.find_element_by_id('q')
#标签交互
serach_input.send_keys('Ipone')
#执行一组js程序
bro.execute_script('window.scrollTo(0,document.body.scrollHeight)')
sleep(3)
#点击按钮
btn = bro.find_element_by_class_name('btn-search')
btn.click()

bro.get('http://www.baidu.com/')
bro.back()
sleep(2)
bro.forward()
sleep(2)
bro.quit()

最後は、12306のシミュレートされたログインです。これは、この検証コードの認識がより複雑なためです。

from selenium import webdriver
from time import sleep
from PIL import Image
from selenium.webdriver import ActionChains
#超级鹰下载示例代码
import requests
from hashlib import md5
class Chaojiying_Client(object):
    def __init__(self, username, password, soft_id):
        self.username = username
        password =  password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
    
    
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
    
    
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def PostPic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
    
    
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {
    
    'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)
        return r.json()

    def ReportError(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
    
    
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()
#设置驱动
bro = webdriver.Chrome('./chromedriver')
#获取网页url
bro.get('https://kyfw.12306.cn/otn/resources/login.html')
sleep(1)
#标签定位到账号登陆,输入账号密码
login_in = bro.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a')
login_in.click()
sleep(2)
#下载验证码图片并保存
#使用bro.save_screenshot('./12306.jpg')进行整张页面的截取并存到本地
bro.save_screenshot('./12306.png')
#确定验证码图片的左上角和右下角坐标(确定裁剪区域)
code_img_ele = bro.find_element_by_xpath('//*[@id="J-loginImg"]')#定位图片
location = code_img_ele.location #验证码图片的左上角坐标下x,y
print(location)
size = code_img_ele.size    #验证码图片的长和宽
print(size)
#确定左上角和右下角坐标
rangle =(int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']))
#验证码图片区域确定下来了
#进行分割
i = Image.open('./12306.png')
code_ing_name = ('./12306yanzhengma.png')
#crop根据指定区域进行裁剪
frame = i.crop(rangle)
frame.save(code_ing_name)
#识别验证码图片
chaojiying = Chaojiying_Client('a1372431588', '970110yy', '905838')	#用户中心>>软件ID 生成一个替换 96001
im = open('./12306yanzhengma.png', 'rb').read()													#本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
print(chaojiying.PostPic(im, 9004)['pic_str'])
sleep(2)
result = chaojiying.PostPic(im, 9004)['pic_str']
all_list =[]#要存储即将被点击的点的坐标[[x1,y1],[x2,y2]]
if '|' in result:
    list_1 = result.split('|')
    print(list_1)
    count_1=len(list_1)
    print(count_1)
    for i in range(count_1):
        xy_list = []
        x = int(list_1[i].split(',')[0])
        y = int(list_1[i].split(',')[1])
        xy_list.append(x)
        xy_list.append(y)
        all_list.append(xy_list)
else:
    x = int(result.split(',')[0])
    y = int(result.split(',')[1])
    xy_list = []
    xy_list.append(x)
    xy_list.append(y)
    all_list.append(xy_list)
print(all_list)
code_img = bro.find_element_by_xpath('//*[@id="J-loginImg"]')
action = ActionChains(bro)
for l in all_list:
    x = l[0]
    y = l[1]
    ActionChains(bro).move_to_element_with_offset(code_img,x,y).click().perform()
username = bro.find_element_by_id('J-userName')
username.send_keys('a1372431588')
sleep(2)
passward = bro.find_element_by_id('J-password')
passward.send_keys('970110yy')
sleep(2)
#点击登录按钮
login = bro.find_element_by_id('J-login')
login.click()

sleep(5)
bro.quit()

コード内のコメントは非常に明確で、誰もが理解できると思います。スーパーイーグルの使用については前の記事を参照してください。ここの検証コードの画像は主にスクリーンショット操作用です。ページ全体がスクリーンショットになった後、検証コードが定義されます。画像が配置されている領域をセグメント化し、それを読み取り、クリックして検証コードの画像認識を完了します。

おすすめ

転載: blog.csdn.net/qwerty1372431588/article/details/106735934