如何使用硒将文本发送到元素而没有名称或ID

时间:2018-12-18 19:37:14

标签: python-3.x selenium selenium-webdriver xpath css-selectors

因此,我正在尝试自动化下载功能之一的报告的过程。我遇到的问题是该特定站点没有用户名和密码字段的名称或ID。以前有没有人处理过这样的问题?

这是用户名字段:

// ==UserScript==
// @name     _delete Adblock blocking nodes
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.
/* global $, waitForKeyElements */

waitForKeyElements ("[id$='adblockinfo']", killNode);

function killNode (jNode) {
    jNode.remove ();
}

这是密码字段:

<input type="text" value="user" placeholder="username@whitehatsec.com" class="form-control" autocomplete="off" style="background-image:
 url(&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAAAXNSR0IArs4c6QAAAUBJREFUOBGVVE2ORUAQLvIS4gwzEysHkHgnkMiEc4zEJXCMNwtWTmDh3UGcYoaFhZUFCzFVnu4wIaiE+vvq6+6qTgthGH6O4/jA7x1OiCAIPwj7CoLgSXDxSjEVzAt9k01CBKdWfsFf/2WNuEwc2YqigKZpK9glAlVVwTTNbQJZlnlCkiTAZnF/mePB2biRdhwHdF2HJEmgaRrwPA+qqoI4jle5/8XkXzrCFoHg+/5ICdpm13UTho7Q9/0WnsfwiL/ouHwHrJgQR8WEwVG+oXpMPaDAkdzvd7AsC8qyhCiKJjiRnCKwbRsMw9hcQ5zv9maSBeu6hjRNYRgGFuKaCNwjkjzPoSiK1d1gDDecQobOBwswzabD/D3Np7AHOIrvNpHmPI+Kc2RZBm3bcp8wuwSIot7QQ0PznoR6wYSK0Xb/AGVLcWwc7Ng3AAAAAElFTkSuQmCC&quot;);
background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 18px; background-position: 98% 50%; cursor: auto;">

2 个答案:

答案 0 :(得分:0)

最坏的情况:您可以使用typeplaceholder属性来定位元素。

Xpath

//input[@type='text'][@placeholder='username@whitehatsec.com']
//input[@type='password'][@placeholder='Enter your password']

This also should work
//input[@placeholder='username@whitehatsec.com']
//input[@placeholder='Enter your password']

CSS选择器

input[type='text'][placeholder='username@whitehatsec.com']
input[type='password'][placeholder='Enter your password']

This also should work
input[placeholder='username@whitehatsec.com']
input[placeholder='Enter your password']

您很有可能错过了一些父元素,该父元素具有一些唯一标识符,例如带有名称或ID的form标签。在html中寻找它们。它们可以提供更好的xpath。

答案 1 :(得分:0)

要将字符序列发送到 Username 字段:

  • css_selector

    driver.find_element_by_css_selector("input.form-control[value='user'][placeholder='username@whitehatsec.com']").send_keys("DarthDobber")
    
  • xpath

    driver.find_element_by_xpath("//input[@class='form-control' and @value='user'][@placeholder='username@whitehatsec.com']").send_keys("DarthDobber")
    

要将字符序列发送到密码字段:

  • css_selector

    driver.find_element_by_css_selector("input.form-control[value='pass'][placeholder='Enter your password']").send_keys("DarthDobber")
    
  • xpath

    driver.find_element_by_xpath("//input[@class='form-control' and @value='pass'][@placeholder='Enter your password']").send_keys("DarthDobber")