如何在Python Selenium中获取href链接

2024-03-28 23:29:08 发布

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

我是Selenium的新手,我正在做一个网站的网页抓取,因为我想获得标签的所有href链接

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

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

在其他代码中,这可以正常工作,但在这里它没有显示任何内容,我还附加了inspect元素区域的图像,我想在其中获取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链接我想得到它

我已将inspect元件的图像包括在下面:

enter image description here


Tags: 代码图像div网页网站链接seleniumcomment
2条回答

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

您还可以通过以下方式使用xpath:

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

相关问题 更多 >