0

我想从下面的html中提取文本,我尝试了不同的方法,但仍然失败。page_id、article_id是随机的。我想得到一个文本列表。

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())
4

1 回答 1

0

我建议使用 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

于 2021-12-01T14:51:35.503 回答