HENNGE / arsenic

Async WebDriver implementation for asyncio and asyncio-compatible frameworks
Other
350 stars 53 forks source link

Get element by XPath #47

Closed nokados closed 5 years ago

nokados commented 5 years ago

I need to get an element by content within it. I don't see anything to do this. In Selenium I could use find_element_by_xpath, for example:

driver.find_element_by_xpath("//button[contains(text(), 'Button text')]")

Is there any way to do this now by arsenic?

ojii commented 5 years ago

No, though you could easily implement it yourself. see https://github.com/HDE/arsenic/blob/4eaafc8f62d6fb0305e66fbb63dcac12b0f35484/src/arsenic/session.py#L98-L104 for how the css-selector based get element works.

philyoun commented 1 year ago

Just to elaborate what @ojii said, below is what I did to use xpath. Open site-packages\arsenic\session.py, in class Element(RequestHelpers):, add

    async def get_element_by_xpath(self, selector: str) -> "Element":
        element_id = await self._request(
            url="/element",
            method="POST",
            data={"using": "xpath", "value": selector}, # not "XPath" nor "xpath selector"
        )
        return self.session.create_element(element_id)

and in class Session(RequestHelpers):, add

    async def get_element_by_xpath(self, selector: str) -> "Element":
        element_id = await self._request(
            url="/element",
            method="POST",
            data={"using": "xpath", "value": selector}, # not "XPath" nor "xpath selector"
        )
        return self.create_element(element_id) # not self.session.create_element()

By doing this, I was able to use equivalent to driver.find_element_by_xpath() in Selenium. Additionally, I needed to use wait_for_element with the xpath, so that I added

    async def wait_for_xpath(self, timeout: int, selector: str) -> Element:
        return await self.wait(
            timeout, partial(self.get_element_by_xpath, selector), NoSuchElement
        )

arsenic library was useful for doing asynchronic webdriver, but lacks a little bit of convenience maybe due to its less usage... Hope it helps anyone.