我訪問了多個Instagram頁面,并點擊了 "關注 "框。有些賬戶是私有的,關注者/粉絲框無法點擊。我想做的是創建一個 "如果 "條件來避免這些不可點擊的情況。我想做的事情編碼如下:
if driver.find_element_by_xpath('//div[@class="QlxVY"]/h2'/span>) == None:
#do something (click on 'following' box and etc.)
上面這個路徑只存在于私人賬戶頁面。它定位了 "這個賬戶是私人的 "短語。因此,我的推理是:如果這句話沒有出現,那是因為這個賬戶不是私人的,我可以繼續點擊 "關注 "框。問題是,'=='運算子后面的'無'并不作業。當我到達一個公共賬戶時,我得到了以下錯誤(我的'if'陳述句被忽略了):
selenium.common.exceptions.NoSuchElementException: 訊息。無法 定位元素。//div[@class="QlxVY"]/h2
我是不是用錯了'無'?我需要使用其他東西嗎? 我已經做了一些研究,但我沒有找到相關的線索......只有一些帖子在談論如何找到一個以前被隱藏的元素的技巧。 謝謝!
uj5u.com熱心網友回復:
你可以試試這兩種方法中的任何一種:-
1- 通過檢查元素的長度1.
element = driver.find_elements_by_xpath('//div[@class="QlxVY"]/h2'/span>)
if len(element)==0。
print('Element not Present ')
#do something (click on 'following' box and etc.)
2- 通過捕捉NoSuchElementException
from selenium.common.exceptions import NoSuchElementException
try:
if driver.find_element_by_xpath('//div[@class="QlxVY"]/h2') 。
print('Element found')
exceptNoSuchElementException。
print('Element not Present')
#do something (click on 'following' box and etc.)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/329423.html
標籤:
