我在從我抓取的元素中獲取 div id 時遇到了一些問題。假設這是我通過類名“產品”提取的區域中的網站代碼
這些列出的 id 的孩子中也有 id,我不想要那些。也不是整頁上的那些。
<div class = "products">
<div>
<div> id= "123">...</div>
<div> id= "456">...</div>
<div> id= "789">...</div>
<div> id= "012">...</div>
</div>
這是我的 selenium/python 代碼。我已經嘗試了幾種解決方案,但我一直無法找到答案。
driver.get("https://genericwebsite.org")
scrape = driver.find_element(By.CLASS_NAME, 'products')
# Here are some solutions I've tried to no avail
ids = scrape.find_elements(By.XPATH, "./child::*").get_attribute('id')
# This one pulls ALL IDS from the children's children as well as maybe the full sites.
ids = scrape.find_elements(By.XPATH,'//*[@id]' )
我嘗試了很多次迭代,但似乎找不到解決方案。我想要的結果如下:
ids = ["123", "456", "789", "012]
uj5u.com熱心網友回復:
試試這個代碼:
ids = []
scrape = driver.find_elements(by=By.XPATH, '//div[@class=\'products\']/div/div')
for item in scrape:
ids.append(item.get_attribute('id'))
print(ids)
使用此代碼,您輸入上面提到的每一個div,并使用方法獲取它們各自的 idget_attribute并將其附加到ids list
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/478016.html
