首页 > 解决方案 > 如何在 Python Selenium 中获取 href 链接

问题描述

我是 Selenium 的新手,我正在对网站进行网页抓取,因为我想获取标签的所有 href 链接。

我使用了以下代码,但无法获取 href 链接。它显示javascript:为输出。

driver.find_element_by_css_selector('div.clFx>a').get_attribute('href')

在其他代码中,这可以正常工作,但在这里它什么也没显示,我还附加了要获取 href 链接的检查元素区域的图像。

我还检查了 Stack Overflow 中的一些答案,并使用了相同的代码,但我仍然无法得到它。

<div class="clFx">
::before
<a class="userName name" href="https://resdex.naukri.com/v2/preview/preview?uniqId=6f44e0e0b95503a44378054b64bdb1cc580e0f001e115d110418475f5808004f130d020214495f5e0b544e170d6&amp;sid=3922138883&amp;paramString=2faf4d57a73f0d419d15309cbc9f5f67134f5108084a5746754e034a571b2513445055524d51250c4b0a1f57504f54030c6&amp;hfFlowName=search&amp;commentSearchType=comment-my,comment-others" target="_blank">Bhimanagoud Patil</a>
::after
</div>

上面的href链接我想得到它。

我在检查元素的图像下方包含了:

在此处输入图像描述

标签: pythonseleniumselenium-webdriverxpathcss-selectors

解决方案


您可以直接使用锚标记来检索与其关联的 href 属性。它在 Web 元素界面中声明,并将 Web 元素属性的值作为字符串返回

   wait = WebDriverWait(driver, 20)
   element= wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Bhimanagoud Patil"))).get_attribute("href")
   print element

或者

wait = WebDriverWait(driver, 20)
element= wait.until(EC.element_to_be_clickable((By.XPATH, "//a[@class='userName name']"))).get_attribute("href")
print element

注意:请在您的解决方案中添加以下导入

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

推荐阅读