【问题标题】:Find div aria label starting with certain text and then extract查找以某些文本开头的 div aria 标签,然后提取
【发布时间】:2022-01-28 03:24:41
【问题描述】:

我正在尝试定位“关注”按钮元素,因为它包含您要关注的用户的文本。

元素:

<div aria-label="Follow @Visiongeo" role="button" tabindex="0" class="css-18t94o4 css-1dbjc4n r-42olwf r-sdzlij r-1phboty r-rs99b7 r-15ysp7h r-4wgw6l r-1ny4l3l r-ymttw5 r-o7ynqc r-6416eg r-lrvibr" data-testid="1676648952-follow" style="background-color: rgb(239, 243, 244);"><div dir="auto" class="css-901oao r-1awozwy r-6koalj r-18u37iz r-16y2uox r-37j5jr r-a023e6 r-b88u0q r-1777fci r-rjixqe r-bcqeeo r-q4m81j r-qvutc0" style="color: rgb(15, 20, 25);"><span class="css-901oao css-16my406 css-bfa6kz r-poiln3 r-1b43r93 r-1cwl3u0 r-bcqeeo r-qvutc0"><span class="css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0">Follow</span></span></div></div>

但问题是,Follow之后的文字,也就是@Visiongeo发生了变化,所以我不想特别定位带有特定文字的元素。

相反,我想定位这个元素,然后获取以“@”开头的文本并将其写入文本文件。

我的代码:

for followers in wait.until(EC.element_to_be_clickable((By.XPATH, "//div[starts-with(@aria-label, 'Follow')]"))):
    file = open("testfile.txt", "a")
    file.write(followers)
    file.write("\n")
    file.close()

我在使用上述代码时收到 TimeoutException 消息。我想我离我打算做的事情还有很长的路要走。

【问题讨论】:

  • 你能分享一个网页链接吗?
  • @Prophet 我想这是 Facebook 帖子;)
  • @DebanjanB 为什么不用 Twitter 或 Instagram 或其他什么?

标签: python selenium


【解决方案1】:

要定位 aria-label 作为 Follow @Visiongeo 的元素,您可以使用以下任一Locator Strategies

  • xpath 1:

    //div[starts-with(@aria-label, 'Follow') and contains(@data-testid, 'follow')]
    
  • xpath 2:

    //div[starts-with(@aria-label, 'Follow') and contains(@data-testid, 'follow')][//span[text()='Follow']]
    
  • xpath 3:

    //div[starts-with(@aria-label, 'Follow') and contains(@data-testid, 'follow')]//span[text()='Follow']//ancestor::div[1]//ancestor::div[1]
    

WebDriverWait 引入你可以使用的visibility_of_all_elements_located()

for followers in wait.until(EC.visibility_of_all_elements_located((By.XPATH, "//div[starts-with(@aria-label, 'Follow') and contains(@data-testid, 'follow')]"))):

要解析你可以使用的关注者的名字:

for followers in [my_elem.get_attribute("aria-label").split("@")[1] for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[starts-with(@aria-label, 'Follow') and contains(@data-testid, 'follow')]")))]:

【讨论】:

  • 我收到错误:对于 wait.until(EC.element_to_be_clickable((By.XPATH, "//div[starts-with(@aria-label, 'Follow') 和 contains(@ data-testid, 'follow')][//span[text()='Follow']]"))): TypeError: 'WebElement' object is not iterable
  • @Cassano 查看更新的答案并告诉我状态
  • 我有一个 for 循环,我试图在 Follow 之后获取包含带有 @ 的用户名的文本。然后将其写入文本文件......我希望你说得对。
  • @Cassano 查看更新的答案并告诉我状态。
  • @Cassano 有什么反馈吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多