我有一個腳本,我使用 Python 從 Selenium 中的網頁獲取一些資料。但是,對于我正在瀏覽的某些頁面,某些元素不存在,這會引發NoSuchElementException錯誤。當元素不存在時,如何回傳空值。我reied使用or None但它仍然拋出錯誤。此外,此元素之后的元素還取決于第一個元素的存在,如下所示:
metadata = driver.find_element(By.PARTIAL_LINK_TEXT, 'Complete metadata on ') or None
metadata_url = metadata.get_attribute('href') or None
dataset_id = metadata_url.split('metadata/')[1] or None
output_dict['datasets'].append({'title': dataset_title, 'url': dataset_link, 'metadata_url': metadata_url})
某些頁面中缺少的元素是metadata. 我希望將該metadata_url欄位填充為null. 請協助解決此問題。
uj5u.com熱心網友回復:
這段代碼:
var = function_call(param) or None
運行該函式,獲取輸出,將此輸出轉換為布林值(請參閱python 中的真實性),如果該輸出為False,則將該變數設定為None。然而,函式 ( find_element, here) 不會回傳 Falsy 值,但NoSuchElementException如果它沒有找到任何東西就會引發例外。這意味著您需要try except在代碼中使用塊而不是or None
try:
metadata = driver.find_element(By.PARTIAL_LINK_TEXT, 'Complete metadata on ')
# If we are at this line, then find_element found something, and we
# can set values for our url and dataset id
metadata_url = metadata.get_attribute('href') # this will be None if there's no href attribute
dataset_id = metadata_url.split('metadata/')[1]
except selenium.common.exceptions.NoSuchElementException:
metadata_url = None
dataset_id = None
在 when metadata_urlis的情況下None,您將需要處理這種情況,因為metadata_url.split它不起作用,它會引發AttributeError: 'NoneType' object has no attribute 'split'.
uj5u.com熱心網友回復:
我猜你正在嘗試在 Python 中使用 JS 語法。您必須先檢查元素是否存在。
if not metadata_url:
return None
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/515484.html
標籤:Python硒
上一篇:抓取資訊并將其存盤到csv檔案中
