我如何 select 嵌套 html 中的元素 by playwright

how do I select element in nest html by playwright

我想从下面的html中提取文本,我尝试了不同的方法,但仍然fail.page_id、article_id是random.I想要得到一个文本列表。

html:

<div id=ufi_{page_id}>
  <div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>    
    <div>
      <div id={article_id}>
          <div></div>
          <div>I want to get the text here</div>
          <div></div>
      </div>
      <div id={article_id2}>
          <div></div>
          <div>I want to get the text here</div>
          <div></div>
      </div>
      <div id={article_id3}>
          <div></div>
          <div>I want to get the text here</div>
          <div></div>
      </div>
    </div>
  </div>
</div>

代码:

comments = page2.query_selector(f'xpath=//div[@id="ufi_{page_id}"]>>div>>//div[5]')
comments_ls = comments.query_selector_all("div>>//div[1]")
if comments:
    for com in comments_ls:
        print(com.text_content())

我建议使用 Playwright codegen 让它为您生成选择器:https://playwright.dev/docs/cli#generate-code

并使用 Locators 而不是 ElementHandles,它们提供简单的实用方法,如 .nth(42).first.last 并自动等待元素出现在给定的选择器中。看这里:https://playwright.dev/python/docs/api/class-locator

有关选择器的更多信息,请参阅此处:https://playwright.dev/docs/selectors