Python Selenium-获取href值 [英] Python Selenium - get href value

查看:634
本文介绍了Python Selenium-获取href值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从网站复制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' object has no attribute 'get_attribute'.使用driver.find_element_by_css_selector(".sc-eYdvao.kvdWiq").get_attribute("href")返回None.但是我不能使用xpath,因为该网站有20+ href,我需要全部复制.使用xpath只会复制一个.

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都归为同一类,即sc-eYdvao kvdWiq.

If it helps, all the 20+ href are categorised under the same class which is sc-eYdvao kvdWiq.

最终,我想复制所有20+ href,并将其导出到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]")))

这篇关于Python Selenium-获取href值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆