如何在selenium中使用元素的innerHTML

在selenium 中使用JavascriptExecutor 修改innerHTML

通过selenium获取的元素无法直接修改元素的内容。通过JavascriptExecutor能够实现对任意可视元素进行innerHTML的修改替换。代码示例如下:

c#代码示例

// An highlighted block
driver.Navigate().GoToUrl(@"https://www.facebook.com/xxxx");
IWebElement postEle = WaitForElementByXPath(driver, "//div[@id='PageComposerPagelet_']//*/div[@class='_1mf _1mj']", 60);
IJavaScriptExecutor ex = (IJavaScriptExecutor)driver;
string postText = AutoUtil.UnescapeHtml(File.ReadAllText("post.log"));
ex.ExecuteScript("arguments[0].innerHTML = '" + postText + "';", postEle);

部分代码说明

WaitForElementByXPath是一个在规定时间定位元素的函数,如果定位不到,则返回Null, 可根据该值来判断页面的加载情况。

// An highlighted block
public IWebElement WaitForElementByXPath(IWebDriver driver, string xpath, int timeout){
	IWebElement ele = null;
	try{
		WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
       ele = wait.Until<IWebElement>((d) => {
             	try{
               	return d.FindElement(By.XPath(xpath));
               }catch{
               	return ele;
               }
             });
    }catch{
    	return ele;
    }
    return ele;
}

UnescapeXml主要对一些html元素进行替换。

// An highlighted block
public static string UnescapeHtml(string escaped){
	return escaped.Replace("&lt;", "<")
  				   .Replace("&gt;", ">")
                  .Replace("&quot;", "\"")
                  .Replace("&apos;", "'")
                  .Replace("&amp;", "&");
 }

随笔

接触selenium,主要是想实现facebook page页面的定期自动发帖子功能。最开始是使用sendkeys,但是facebook页面大多使用js进行动态渲染且tag一般都div与span,只查到上述方法可以实现innerHTML的替换更新。

如果你觉得对你有帮助,就打赏点吧
如果对你有帮助,就赏点吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值