我試圖找到按鈕元素“關注”,因為它包含您要關注的用戶的文本。
元素:
<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 訊息。我想我離我打算做的事情還差得很遠。
uj5u.com熱心網友回復:
要找到與元素aria-label作為后續@Visiongeo您可以使用以下的定位策略:
路徑1:
//div[starts-with(@aria-label, 'Follow') and contains(@data-testid, 'follow')]路徑2:
//div[starts-with(@aria-label, 'Follow') and contains(@data-testid, 'follow')][//span[text()='Follow']]路徑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')]")))]:
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/397247.html
