How to get element attribute by xpath in pyppeteer

2.3k views Asked by At

I'm trying to use ElementHandle.Jeval() to get element style attribute through Pyppeteer. But the problem is I can only address the element by xpath since the element class is dynamically generated.

However, the ElementHandle.Jeval() requries selector as one of the parameters.

I've tried:

element = await iframe.Jx('//*[@id="root"]/main/div[1]/div/div[9]/div[1]/div[2]/div[2]/div/div[2]')
style = await element[0].Jeval(pageFunction='node => node.getAttribute("style")')

It still requires selector. And I tried to find a way to get selector from the ElementHandle I addressed through xpath, but didn't find out a method allow me to do so.

and:

xpath = '//*[@id="root"]/main/div[1]/div/div[9]/div[1]/div[2]/div[2]/div/div[2]'
style = await iframe.Jeval(xpath, pageFunction='node => node.getAttribute("style")')
-------------------------------
raise ElementHandleError('Evaluation failed: {}'.format(
pyppeteer.errors.ElementHandleError: Evaluation failed: DOMException: Failed to execute 'querySelector' on 'Document': '//*[@id="root"]/main/div[1]/div/div[9]/div[1]/div[2]/div[2]/div/div[2]' is not a valid selector.
at __pyppeteer_evaluation_script__:1:33

If anyone can figure this out, please let me know. Thanks.

-----------------update---------------

I figured out through editing the source code:

#!element_handle.py
# elementHandle = await self.querySelector(selector)
elementHandle = selector
if not elementHandle:
    raise ElementHandleError(
        f'Error: failed to find element matching selector "{selector}"'
    )
result = await self.executionContext.evaluate(
    pageFunction, elementHandle, *args)
await elementHandle.dispose()
return result

However, I don't want to do so. If anyone have a better way, let me know. Thanks.

0

There are 0 answers