我正在嘗試從標簽中獲取內容,但NoSuchElement即使從具有相同級別的另一個標簽中獲取內容成功,它也會提高 。
這是網站鏈接:https : //soundcloud.com/pastlivesonotherplanets/sets/spell-jars-from-mars
這是我訪問的html代碼:
<div class="fullHero__tracksSummary">
<div class="playlistTrackCount sc-font">
<div class="genericTrackCount sc-font large m-active" title="16 tracks">
<div class="genericTrackCount__title">16</div>
<div class="genericTrackCount__subtitle"> Tracks </div>
<div class="genericTrackCount__duration sc-type-small sc-text-body sc-type-light sc-text-secondary">56:07</div>
</div>
</div>
</div>
我正在嘗試使用以下代碼獲取播放串列的持續時間:
try:
tmp=driver.find_element_by_xpath("//div[@class='fullHero__tracksSummary']")
duration=tmp.find_element_by_class_name("genericTrackCount__duration sc-type-small sc-text-body
sc-type-light sc-text-secondary").get_attribute('textContent')
print(duration)
except:
print("None")
NoSuchElement即使其他兩個標簽成功,它也會引發錯誤。
有什么問題,我該如何解決?
感謝您的時間。
uj5u.com熱心網友回復:
我認為您可以嘗試直接使用 xpath//div[contains(@class, 'duration')]或
//div[contains(@class, 'playlistTrackCount')]/descendant::div[contains(@class, 'duration')]
uj5u.com熱心網友回復:
在不查看頁面的情況下,您可能需要等待元素加載。
您可以使用time.sleep(5)5 作為等待的秒數或WebDriverWait(driver, 20)預期條件
所以你的代碼看起來像
import expected_conditions as EC
WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CLASS_NAME, '"genericTrackCount__duration sc-type-small sc-text-body
sc-type-light sc-text-secondary"))).text
也可能 get_attribute('textContent')失敗了,你可以使用.text
uj5u.com熱心網友回復:
你也可以使用 xapth 來做到這一點,如下所示:
`WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//*[@]/div[1]'))).text
#進口:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/346342.html
