【问题标题】:How to get href link in Python Selenium如何在 Python Selenium 中获取 href 链接
【发布时间】:2020-04-19 16:58:39
【问题描述】:

我是 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链接我要搞定。

我已在检查元素的图像下方添加:

【问题讨论】:

    标签: python selenium selenium-webdriver xpath css-selectors


    【解决方案1】:

    您可以直接使用锚标记来检索与其关联的 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
    

    【讨论】:

    • 感谢您的帮助,但我已经使用了该代码,它再次显示 javascript: 作为结果输出。基本上,当我点击链接时,它会打开,但是当我尝试获取 href 时,它会显示 javascript:
    • 你能分享你的链接吗?
    • 这已经是有问题的共享 -
      ::before Bhimanagoud Patil ::after
    • 那是您的 DOM,我要求您在检索元素时尝试链接
    • resdex.naukri.com/v2/preview/…" target="_blank">Bhimanagoud Patil href 标签
    【解决方案2】:

    你也可以这样使用xpath:

    driver.find_element_by_xpath('//div[@class="clFx"]/a').get_attribute('href')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 1970-01-01
      • 2021-12-03
      • 2020-02-28
      • 1970-01-01
      相关资源
      最近更新 更多