Python Selenium获取href valu

2024-10-01 13:40:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从网站复制href值,html代码如下:

<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")返回{}。但是我不能使用xpath,因为这个网站有20+的href,我需要全部复制。使用xpath只能复制一个。在

如果有帮助的话,所有的20+href都被归类到同一个类下,sc-eYdvao kvdWiq。在

最后,我想复制所有的20+href并将它们导出到csv文件。在

感谢任何可能的帮助。在


Tags: parkgetby网站driverattributefindselector
3条回答

你想要吗driver.find_元素如果不止一个元素。这将返回一个列表。对于css选择器,您要确保为具有子href的类选择

elems = driver.find_elements_by_css_selector(".sc-eYdvao.kvdWiq [href]")
links = [elem.get_attribute('href') for elem in elems]

您可能还需要等待条件,以便css选择器找到的所有元素都存在。在

^{pr2}$

XPATH

//p[@class='sc-eYdvao kvdWiq']/a

返回要查找的元素。在

将数据写入CSV文件与抓取挑战无关。只要试着看看例子,你就能做到。在

尝试类似于:

elems = driver.find_elements_by_xpath("//p[contains(@class, 'sc-eYdvao') and contains(@class='kvdWiq')]/a")
for elem in elems:
   print elem.get_attribute['href']

相关问题 更多 >