3 回答

TA貢獻1895條經驗 獲得超3個贊
編輯:
你得到了重復的結果,因為從循環(huán)它選擇根元素//它應該是相對的或選擇子元素,./但它仍然不起作用,并且可能是分裂錯誤。但嘗試使用 CSS 選擇器
for map_element in maps_elements:
# select relative but failed
#title = map_element.find_by_xpath("./div[contains(@class,'dbg0pd')]/span")
title = map_element.find_by_css("div[class*='dbg0pd'] > span").text
print(title)
變量中的錯字,s從
title = maps_elements.....
#title = map_element.....

TA貢獻1864條經驗 獲得超2個贊
這是正確的,因為您不能在 for 循環(huán)中聲明一個變量,然后在其中創(chuàng)建該變量。您需要在初始化循環(huán)之前創(chuàng)建變量才能使其工作。
title_elements = browser.find_by_xpath("//div[contains(@class,'dbg0pd')]/span")
for title_element in title_elements:
title = title_element.text
print(title)

TA貢獻1982條經驗 獲得超2個贊
更改您的代碼:
maps_elements = browser.find_by_xpath("//div[contains(@class,'VkpGBb')]")
for map_element in maps_elements:
# print(map_element.text)
title = maps_elements.find_by_xpath("//div[contains(@class,'dbg0pd')]/span").text
print(title)
到
title_elements = browser.find_by_xpath("//div[contains(@class,'dbg0pd')]/span")
for title_element in title_elements:
title = title_element.text
print(title)
添加回答
舉報