background

  • Some time ago, I wrote an automatic recording to generate Python Seleinum code for QA team, but the generated code query did not deal with the delay waiting, resulting in poor code stability and easy failure of element query

solution

  • Overwrites the two methods of the element query, find_ELEMENT and find_Elements, without modifying the original code

implementation

Code implementation is relatively simple, directly paste the code

selenium_monkey.py

import time from selenium.webdriver import Chrome from selenium.webdriver.common.by import By def wait_element(self, End_time = time.time() + timeout while True: If self.find_elements(by=by, value=value): break if time.time() > end_time: Def find_element_ext(self, by= by.id, value=None): Wait_element (self, by=by, value=value) Return super(Chrome, self).find_element(by=by, value=value) def patch_find_element(): Find_element = find_element_extCopy the code

test_selenium.py

import time import logging from selenium.webdriver import Chrome from selenium_monkey import patch_find_element Patch_find_element () # Logging.basicconfig (level= logging.info, level= logging.info) format='%(asctime)s [%(name)s:%(lineno)d] [%(levelname)s]- %(message)s') logger = logging.getLogger(__name__) class TestSeleiumCase: # Execute pytest -s test_seleinum.py def test_find_element_wait(self): context1 = Chrome(executable_path=r"C:\Users\dong\Downloads\chromedriver.exe") context1.get("https://www.baidu.com/") context1.find_element_by_css_selector(css_selector="input[name=\"wd\"]").click() context1.find_element_by_css_selector(css_selector="input[name=\"wd\"]").send_keys("python") time.sleep(2) context1.close()Copy the code