問題描述
我正在嘗試從網(wǎng)站復(fù)制 href 值,html 代碼如下所示:
I am trying to copy the href value from a website, and the html code looks like this:
<p class="sc-eYdvao kvdWiq">
<a href="https://www.iproperty.com.my/property/setia-eco-park/sale-
1653165/">Shah Alam Setia Eco Park, Setia Eco Park
</a>
</p>
我試過 driver.find_elements_by_css_selector(".sc-eYdvao.kvdWiq").get_attribute("href")
但它返回 'list' 對象沒有屬性 'get_attribute'代碼>.使用
driver.find_element_by_css_selector(".sc-eYdvao.kvdWiq").get_attribute("href")
返回 None
.但我不能使用 xpath,因?yàn)樵摼W(wǎng)站有 20+ href 我需要全部復(fù)制.使用 xpath 只會復(fù)制一個.
I've tried driver.find_elements_by_css_selector(".sc-eYdvao.kvdWiq").get_attribute("href")
but it returned 'list' object has no attribute 'get_attribute'
. Using driver.find_element_by_css_selector(".sc-eYdvao.kvdWiq").get_attribute("href")
returned None
. But i cant use xpath because the website has like 20+ href which i need to copy all. Using xpath would only copy one.
如果有幫助,所有 20 多個 href 都?xì)w入同一類,即 sc-eYdvao kvdWiq
.
If it helps, all the 20+ href are categorised under the same class which is sc-eYdvao kvdWiq
.
最終我想復(fù)制所有 20+ href 并將它們導(dǎo)出到 csv 文件.
Ultimately i would want to copy all the 20+ href and export them out to a csv file.
感謝任何可能的幫助.
推薦答案
如果有多個元素,您需要 driver.find_elements.這將返回一個列表.對于 CSS 選擇器,您要確保選擇那些具有子 href 的類
You want driver.find_elements if more than one element. This will return a list. For the css selector you want to ensure you are selecting for those classes that have a child href
elems = driver.find_elements_by_css_selector(".sc-eYdvao.kvdWiq [href]")
links = [elem.get_attribute('href') for elem in elems]
您可能還需要一個等待條件來等待由 css 選擇器定位的所有元素.
You might also need a wait condition for presence of all elements located by css selector.
elems = WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".sc-eYdvao.kvdWiq [href]")))
這篇關(guān)于Python Selenium - 獲取href值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!