diff --git a/DrissionPage/driver_element.py b/DrissionPage/driver_element.py index 3c352fe..29cd994 100644 --- a/DrissionPage/driver_element.py +++ b/DrissionPage/driver_element.py @@ -23,6 +23,7 @@ class DriverElement(DrissionElement): def __init__(self, ele: WebElement, page=None): super().__init__(ele, page) + self._select = None def __repr__(self): attrs = [f"{attr}='{self.attrs[attr]}'" for attr in self.attrs] @@ -55,7 +56,7 @@ class DriverElement(DrissionElement): @property def tag(self) -> str: """返回元素类型""" - return self._inner_ele.tag_name + return self._inner_ele.tag_name.lower() @property def attrs(self) -> dict: @@ -158,7 +159,19 @@ class DriverElement(DrissionElement): """返回当前元素的::after伪元素内容""" return self.get_style_property('content', 'after') + @property + def select(self): + """返回专门处理下拉列表的Select类,非下拉列表元素返回False""" + if self._select is None: + if self.tag != 'select': + self._select = False + else: + self._select = Select(self) + + return self._select + # -----------------共有函数------------------- + def texts(self, text_node_only: bool = False) -> list: """返回元素内所有直接子节点的文本,包括元素和文本节点 \n :param text_node_only: 是否只返回文本节点 @@ -449,32 +462,6 @@ class DriverElement(DrissionElement): return img_path - def select(self, text: str) -> bool: - """选择下拉列表中子元素 \n - :param text: 要选择的文本 - :return: 是否选择成功 - """ - from selenium.webdriver.support.select import Select - ele = Select(self.inner_ele) - - try: - ele.select_by_visible_text(text) - return True - except Exception as e: - print(e) - return False - - @property - def selected_option(self): - """返回下拉列表中被选中的option元素 \n - :return: DriverElement对象或None - """ - if self.tag != 'select': - return None - else: - ele = self.run_script('return arguments[0].options[arguments[0].selectedIndex];') - return None if ele is None else DriverElement(ele, self.page) - def set_attr(self, attr: str, value: str) -> bool: """设置元素属性 \n :param attr: 属性名 @@ -787,3 +774,110 @@ class ElementsByXpath(object): else format_html(x) for x in get_nodes(the_node, xpath_txt=self.xpath) if x != '\n']) + + +class Select(object): + def __init__(self, ele: DriverElement): + if ele.tag != 'select': + raise TypeError(f"Select only works on