我需要在亞馬遜頁面上找到,就像這樣。如果該類存在,我需要設定變數 x == 0,如果它不存在,我需要設定變數 x == 1。
我試過這段代碼,但它不起作用。我怎樣才能檢查這個?
try:
couponBadge = driver.find_elements_by_class_name("a-icon a-icon-addon couponBadge")
if couponBadge != None:
x == 0
else:
x == 1
except AttributeError:
print("error")
uj5u.com熱心網友回復:
您需要使用一個等號而不是兩個等號來分配給變數。
例如 x = 1
看起來 Selenium 的get_elements_by_class_name函式也只支持輸入單個類名,而不是您的示例中顯示的多個類名,因此您可能需要查看driver.find_element_by_css_selector().
例如 driver.find_element_by_css_selector('.a-icon.a-icon-addon.couponBadge')
uj5u.com熱心網友回復:
請試試這個:
couponBadge = driver.find_elements_by_class_name("a-icon a-icon-addon couponBadge")
if couponBadge:
x = 0
else:
x = 1
driver.find_elements_by_class_name回傳一個串列。
如果存在與此定位器匹配的元素,則串列將為非空,因此它將被解釋為布林值 True。否則將被解釋為 False。
同樣要為變數賦值,您應該使用單個=,而不是==.
==用于比較。
此外,正如 CrunchyBox 所提到的,您應該使用find_element_by_css_selector,而不是get_elements_by_class_name.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/349826.html
