简体   繁体   English

JavaScript:将ID属性注入到 <input> 通过XPATH标记

[英]JavaScript : injecting ID attribute to an <input> tag by XPATH

I'm trying to automate something using selenium, issue is that the tag has no ID, so I'm finding the control using xpath and JS as so: 我正在尝试使用selenium自动化一些问题,问题是该标签没有ID,因此我正在使用xpath和JS找到控件,如下所示:

document.evaluate('/html/body/header[2]/div[2]/div/div[1]/div[1]/div/div/div/form/fieldset/div[1]/input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue document.evaluate('/ html / body / header [2] / div [2] / div / div [1] / div [1] / div / div / div / form / fieldset / div [1] / input', document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue

and this is the response from chrome's console: 这是chrome控制台的响应:

<input> type="file" data-autosubmitoff="true" accept=".xls,.csv,.xlsx" name="File" class="hidden"></input>

which means it found my control by xpath, now I want to inject an ID so that I can refer to it from selenium. 这意味着它通过xpath找到了我的控件,现在我想注入一个ID,以便可以从Selenium中引用它。

I tried to do it like this: 我试图这样做:

document.evaluate('/html/body/header[2]/div[2]/div/div[1]/div[1]/div/div/div/form/fieldset/div[1]/input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.innerHTML='input id="UploadedFileFilter" type="file" data-autosubmitoff="true" accept=".xls,.csv,.xlsx" name="File" class="hidden">'

basically rewriting the whole tag with the ID in it and the console responds accordingly with this answer: 基本上重写了其中带有ID的整个标签,控制台相应地回答了以下答案:

input id="UploadedFileFilter" type="file" data-autosubmitoff="true" accept=".xls,.csv,.xlsx" name="File" class="hidden">"

PERFECT! 完善! but when I look in the DOM the Input tag is still the old one, what am I getting wrong? 但是当我查看DOM时,Input标记仍然是旧标记,这是怎么回事?

Thanks. 谢谢。

Instead of editing the HTML directly try just setting the id value like this: 与其直接编辑HTML,不如尝试像这样设置id值:

var path = '/html/body/header[2]/div[2]/div/div[1]/div[1]/div/div/div/form/fieldset/div[1]/input';
var element = document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
element.id = 'UploadedFileFilter';

It's also worth noting that innerHTML is the HTML contained within the element. 还值得注意的是, innerHTML是元素内包含的HTML。 To edit the HTML of the element itself you may be able to use outerHTML . 要编辑元素本身的HTML,您可以使用outerHTML

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM