python - 如何在 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&sid=3922138883&paramString=2faf4d57a73f0d419d15309cbc9f5f67134f5108084a5746754e034a571b2513445055524d51250c4b0a1f57504f54030c6&hfFlowName=search&commentSearchType=comment-my,comment-others" target="_blank">Bhimanagoud Patil</a>
::after
</div>
上面的href链接我想得到它。
我在检查元素的图像下方包含了:
解决方案
您可以直接使用锚标记来检索与其关联的 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
推荐阅读
- java - 当我运行springboot时,控制台显示此错误,我该怎么做才能修复它?
- c# - 打印出素数从小到大的成功发展
- python - 有没有办法用同名的变量替换字符串?
- reactjs - “react-dnd-html5-backend”没有导出成员“HTML5Backend”
- pine-script - 交易观点 - 当价格上涨到某个价格之上时如何触发止盈?
- python - 无法修复:RuntimeError:梯度计算所需的变量之一已被就地操作修改
- node.js - 为什么 Promise.race 不能在 kafkajs eachMessage 回调中解析
- javafx - 标签不会更改其在用户元素中的大小。(扩展控制)
- javascript - SVG 转换
标记到包含 base64 PNG URI 的标记(阅读更多) - python - 如果只读,有没有办法让 ttk.combobox 不将背景颜色更改为灰色?