How to get texts in iframe using query_selector_all with Playwright

Viewed 51

I want to get text data from iframe on a webpage using Playwright with Python. As the data in the iframe, it does not work when I try use page.query_selector_all directly.

For example, below works well, but it's not a solution I want.

inner_text = await page.frame_locator('iframe#mypage_frm').locator('//*[@id="List"]').inner_text()
inner_html = await page.frame_locator('iframe#mypage_frm').locator('//*[@id="List"]').inner_html()
print(inner_text)
print(inner_html)

I need to use query_selector_all to get data through the loop in the iframe because the data consists of recurring loop. I tried many ideas, but no way work. For example, below does not work.

await page.frame_locator('iframe#mypage_frm').query_selector('//*[@id="List"]')

Please advise how to use query_selector_all (or just query_selector) in iframe. Thank you.

1 Answers

You can use a selector to return a ElementHandle for the frame, and then use the content_frame method to get a handle to the content frame for the iframe. This Frame object supports usage of query_selector:

iframe_handle = await page.wait_for_selector("#mypage_frm")
iframe = await iframe_handle.content_frame()
await iframe_handle.query_selector('//*[@id="List"]')

Alternatively, you can also use page.frame to create frame objects

Related