我正在抓取一個頁面,在其中查找以下串列中的所有元素:
description = driver.find_elements(By.XPATH, "//div[contains(@class,'list') and h1/text()='Values']/ul[@class='bullet-list']")
但是在給定的頁面上它們的數量未知,大多在 3-10 之間。每個串列中還有未知數量的專案(每個串列中的專案數量不匹配)。如果我這樣搜索串列項:
description = driver.find_elements(By.XPATH, "//div[contains(@class,'list') and h1/text()='Values']/ul[@class='bullet-list']/li")
我得到了所有串列項,但現在我不知道它們屬于哪個串列。
我想做的是這樣的
description = driver.find_elements(By.XPATH, "//div[contains(@class,'list') and h1/text()='Values']/ul[@class='bullet-list']")
for x in range(len(description)):
values = driver.find_elements(By.XPATH, f"{description[x].xpath}/li")
for y in values:
b_list.append(y.text)
a_list.append(b_list)
所以你可以明白為什么我需要知道專案來自哪個串列,以便它們可以在同一個 [] 中。
我可以使用絕對 xpath 來解決這個問題,但如果我能找到一種使用相對 xpath 的方法,那就更好了。
uj5u.com熱心網友回復:
如果您想從多個串列中獲取專案,您可以嘗試
lists = []
description = driver.find_elements(By.XPATH, "//div[contains(@class,'list') and h1='Values']/ul[@class='bullet-list']")
for _list in description:
lists.append([li.text for li in _list.find_elements(By.XPATH, './li')])
print(lists)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/345990.html
上一篇:無法使用Selenium填寫表單:AttributeError:'WebDriver'objecthasnoattribute'get_element_by_xpath&
