【问题标题】:How to convert Python Code to Robot Framework如何将 Python 代码转换为机器人框架
【发布时间】:2019-11-29 05:17:17
【问题描述】:

我正在尝试自动化 CAPTCHA,我也为此编写了一个 python 代码。现在我被困在一个点上,即我无法通过创建自定义库在 Robot Framework 中调用它。

from PIL import Image
import string
import json
import os
import time
import pytesseract
import cv2
import numpy as np
import re
from tesserocr import PyTessBaseAPI,PSM, OEM
import time
import logging

captcha_url = "http://www.mca.gov.in/mcafoportal/getCapchaImage.do"
regex = re.compile(r'[\n\r\t ]')#special char plus space

def get_captcha2(session):
    res = session.get(captcha_url, timeout = 10)
    with open("a.jpg", "wb") as f: f.write(res.content)
    img = Image.open("a.jpg")
    captcha = pytesseract.image_to_string(img, config='--psm 8 --oem 0 -c tessedit_char_whitelist=abcdefghijklmnopqrstuvwxyz')
    logging.info("cap: %s"%captcha)
    while not (captcha.islower() and captcha.isalpha() and len(captcha) in  [6,7]):
        time.sleep(.05)
        res = session.get(captcha_url)
        with open("a.jpg", "wb") as f: f.write(res.content)
        img = Image.open("a.jpg")
        captcha = pytesseract.image_to_string(img, config='--psm 8')
        logging.info("cap: %s"%captcha)
    return captcha



def get_captcha(req):
    api = PyTessBaseAPI(psm=PSM.SINGLE_WORD, oem = 0)
    api.SetVariable("tessedit_char_whitelist", "abcdefghijklmnopqrstuvwxyz")
    res = req.get(captcha_url, timeout = 10)
    #with open("a.jpg", "wb") as f: f.write(res.content)
    clean_captcha_image(api, res.content)
    captcha = regex.sub("", api.GetUTF8Text())
    conf = api.MeanTextConf()
    cnt = 0
    while (len(captcha) not in  [6,7] or conf<=70) and cnt<=3:
        res = req.get(captcha_url, timeout = 10)
        clean_captcha_image(api, res.content)
        captcha = regex.sub("", api.GetUTF8Text())
        conf = api.MeanTextConf()
        cnt += 1
    return captcha


def break_point(arr):
    for i,n in arr:
        if n:
            break
    return i

def convert_numpy_ipl(trimmed):
    h,w = trimmed.shape
    c = 1
    iplimage = cv.CreateImageHeader((w,h), cv.IPL_DEPTH_8U, c)
    cv.SetData(iplimage, trimmed.tostring(),trimmed.dtype.itemsize * c * (w))
    return iplimage

def clean_captcha_image(api, c_content):
    try:
        arr = np.fromstring(c_content, np.uint8)
        image = cv2.imdecode(arr,0)
        th = cv2.threshold(image,50,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)[1]

        iplimage = Image.fromarray(th)
        api.SetImage(iplimage)
    except Exception as e:
        print("Unexpected error on clean ",e)


def parse_captcha(filename):
    return pytesseract.image_to_string(Image.open(filename))

if __name__ == "__main__":
    import requests
    session = requests.Session()
    session.headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"}
    get_captcha2(session)

我尝试使用 Robot Framework 自动执行相同的操作,但由于会话超时而失败。在我尝试下载图片的那一刻,验证码发生了变化。

【问题讨论】:

  • 标题可能会产生误导,因为您正试图使用 Robot Framework 中的 Python 代码,而不是 convert 它,对吧?

标签: python selenium robotframework


【解决方案1】:

【讨论】:

    【解决方案2】:

    按照以下步骤从机器人文件中获取调用的函数,

    第 1 步:使用您的函数创建一个 python 文件,如下所示 C:\Users\kgurupra\pyfirst.py

    def message(msg):
        print ('your message is ' + msg)
        return True
    

    第 2 步:确保您的 .py 文件位于 PYTHONPATH 中 - 这是非常重要的一步

    第三步:创建你的机器人文件,如下所述,

    *** Settings ***
    Library           String
    Library     Collections
    Library         Selenium2Library
    **Library         pyfirst.py**
    
    *** Test Cases ***
    Case1
        message    "hello"
    

    Step4: 你应该看到如下输出,

    
    (rf1) C:\Users\kgurupra>robot rbpy.robot
    ==============================================================================
    Rbpy
    ==============================================================================
    Case1                                                                 | PASS |
    ------------------------------------------------------------------------------
    Rbpy                                                                  | PASS |
    1 critical test, 1 passed, 0 failed
    1 test total, 1 passed, 0 failed
    ==============================================================================
    Output:  C:\Users\kgurupra\output.xml
    Log:     C:\Users\kgurupra\log.html
    Report:  C:\Users\kgurupra\report.html
    
    

    【讨论】:

    • py 文件不需要在 PYTHONPATH 中 - 框架应该能够找到它。您编写它的方式,如果它与 .robot 文件在同一个目录中,它将被找到 - 而不是在路径中。如果您将其指定为../mylib.py,它将在父文件夹中查找它。将它添加到 PYTHONPATH 的重要步骤只是一个快捷方式——任何 python 程序都可以访问它,包括 Robot Framework;但这实际上不是很好——你只是在用随机的模块和方法污染你的路径。
    • 无论如何,我认为您的回答没有解决 OP 的问题,他说他创建了一个库。这只是重复用户指南库部分中的介绍。
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2022-10-05
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 2020-06-28
    • 2017-06-06
    • 1970-01-01
    相关资源
    最近更新 更多