将Selenium WebDriver字段写入txt文件

时间:2019-07-04 18:42:45

标签: python selenium

我所做的是编写一个小程序来读取JSON数据并将其转换为硒代码。

基本示例代码:

    def write_to_debug_file(self, debug_info):
        with open("debug/debug_file.txt", "a+") as file:
            file.write("%s\n" % debug_info)


    def get_identifier(self, identifier, html_identifier):
        final_identifier = ""
        if identifier == "id":
            final_identifier = self.driver.find_element_by_id(html_identifier) 
        elif identifier == "name":
            final_identifier = self.driver.find_element_by_name(html_identifier)
        return final_identifier


    def prepare_fields(self, url_or_identifier, html_identifier, name_this, action_to_take, username, password, email):
        #{
        #   "register": [
        #       "https:\/\/www.thesite.com\/register.php|0|0|SEND_URL",
        #       "name|username|0|SEND_USERNAME"
        #   ]
        #}
        selenium_field = ""
        if action_to_take == "SEND_URL":
            selenium_field == self.driver.get(url_or_identifier)
        elif action_to_take == "SEND_USERNAME":
            selenium_field == self.driver + self.get_identifier(url_or_identifier, html_identifier).send_keys(username)       
        else:
            pass
        return selenium_field


    def mode_register(self, username, password, email, captcha_key, _sleep, _json):       
        try:

            json_string = json.loads(_json)
            if "register" in json_string:
                for register in json_string["register"]:
                    register_parts = register.split("|")
                    selenium_action = self.prepare_fields(register_parts[0], register_parts[1], register_parts[2], register_parts[3], username, password, email)
                    self.write_to_debug_file("sleep(" + str(_sleep) + ")" + selenium_action)

            if "You have successfully created your account" in self.driver.page_source:
                return True
            else:
                return False

        except Exception as e: 
            self.print_exception()

脚本工作正常,我遇到的问题是将selenium_action部分写入.txt文件,以便我可以对其进行仔细调试,目前出现错误:

“ selenium_action = self.prepare_fields(register_parts [0],register_parts [1],register_parts [2],register_parts [3],用户名,密码,电子邮件)”):不支持的操作数类型)+:“ WebDriver”和“ NoneType”

我想不出一种将字段写入文件的简便方法,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

我宁愿使用内置的记录程序包将任何日志写入文件中以进行调试。 无需编写自己的函数,只需使用日志记录包即可。

import logging

logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This will get logged to a file')

可以使用多个日志记录级别。

PS:您收到的错误是因为函数prepare_fields返回None。