如何使用硒获取“ href”链接?

时间:2019-06-17 06:00:14

标签: python selenium

我使用selenium-python。并且我要制作“ 电子邮件验证用例”。在测试案例中,我转发了“ a href ”链接。

是的。我只知道使用find_element_by_partial_link_text就可以了。但我不明白在我的情况下是行不通的。

这是案例

<tbody> 
<tr>
  <td style = "padding-bottom:40px;">
     <a href="(auth link)" target="blank" style="(some style)">Verify address</a>
  </td>
</tr>
</tbody>

我正在使用

  1. find_element_by_partial_link_text("Verify") / ("Verify Address") / ("address")
  2. find_element_by_css_selector("padding-bottom").get_attribute('href')

但有make'selenium.common.exceptions.NoSuchElementException'例外:<< / p>

,然后尝试<br> find_element_by_xpath(),但auth-link每次都在变化。

如何获取 href 链接并单击此链接?

2 个答案:

答案 0 :(得分:0)

尝试引入webdriverwait。

我要将link_text更改为partial_link_text,只需确保UI中仅存在一个Verify address链接,否则代码将不会引发任何错误,只需选择第一个元素。

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, 'Verify address')))

只需单击即可使用:

element.click()

要获取 href ,请使用:

element.get_attribute('href')

您可以关注此官方Link,了解更多信息。

您需要导入以下内容:

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

如果您还有其他顾虑,请告诉我。

答案 1 :(得分:0)

您也可以尝试使用文本进行XPATH。尝试以下列表中的任何一个:

$request_body = json_decode(file_get_contents('php://input'));
$mailbox = $request_body->mailbox;
$username = $request_body->username;
$password = $request_body->password;

$imapResource = imap_open('{'.$mailbox.'}Inbox', $username, $password);

if($imapResource === false){
    echo imap_last_error();
    throw new Exception(imap_last_error());
}

在find元素之后,您可以进行get_attributes或任何其他操作。

希望它能解决您的问题。