【发布时间】:2017-02-05 19:56:04
【问题描述】:
下面的JS代码(通过python selenium运行)在文档中搜索文本,定位标签并提取HTML元素的css属性。
styleJSON = driver.execute_script("""function getElementByXpath(path){return document.evaluate(path, document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);}function getPathTo(element) {if(element.id!=='') return 'id("'+element.id+'")';if (element===document.body) return '//'+element.tagName; var ix= 0;var siblings= element.parentNode.childNodes; for (var i= 0; i<siblings.length; i++) {var sibling= siblings[i];if (sibling===element)return getPathTo(element.parentNode)+'/'+element.tagName+'['+(ix+1)+']';if (sibling.nodeType===1 && sibling.tagName===element.tagName)ix++;}}var not_found=[],styleSheet=[],pos,temp;try{var corpus=JSON.parse(arguments[0]);console.log(corpus);for(var k = 0; k < corpus.length; k++){pos=0; elements = getElementByXpath('//*[normalize-space(text())=normalize-space('+cleanStringForXpath(corpus[k])+')]');elem=elements.iterateNext();if(!elem){not_found.push(corpus[k]);} while(elem) { pos++;temp = {'corpus': corpus[k], 'font_size':window.getComputedStyle(elem).fontSize, 'font_color':window.getComputedStyle(elem).color,'font_weight':window.getComputedStyle(elem).fontWeight,'font_family':window.getComputedStyle(elem).fontFamily,'tag': elem.tagName,'xpath':getPathTo(elem),'pos':pos,'text_decoration':window.getComputedStyle(elem).textDecoration}; if(temp.tag!=='SCRIPT' || temp.tag!=='TITLE'){styleSheet.push(temp);console.log(temp);}elem=elements.iterateNext();}}}catch(err){console.log(err);}console.log(not_found);return JSON.stringify({stylesheet:styleSheet,not_found: not_found});""", json.dumps(corpus, ensure_ascii=False, encoding='utf-8'))
我的问题是传入带有单引号和双引号的文本时。我尝试使用 link 中的函数 cleanStringForXpath 来清理传递给 xpath query'//*[normalize-space(text())=normalize-space('+cleanStringForXpath(corpus[k])+')]' 的文本,但不能让它工作。尝试在python中通过简单的连接"""..."""+"""..."""将它添加到execute_script,尝试将函数作为参数传递给execute_script,然后调用Function构造函数,尝试在python中使用%s修饰符,但这些都没有产生任何结果结果。这可能是什么问题?
【问题讨论】:
标签: javascript python xpath selenium-webdriver automated-tests