Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过selenium动态创建新元素_Python_Selenium_Web Scraping - Fatal编程技术网

Python 通过selenium动态创建新元素

Python 通过selenium动态创建新元素,python,selenium,web-scraping,Python,Selenium,Web Scraping,我需要的是在html文档的头部添加一个脚本标记。我正在使用下面的代码,但是当我查看页面源代码时,脚本不在那里。 提前谢谢大家, driver = webdriver.Chrome() driver.get("http://www.x.org") execu = ''' var scr = document.createElement('script'); scr.type = 'text/javascript'; scr.text = `let calls = (function(){

我需要的是在html文档的头部添加一个脚本标记。我正在使用下面的代码,但是当我查看页面源代码时,脚本不在那里。 提前谢谢大家,

driver = webdriver.Chrome()
driver.get("http://www.x.org")


execu = '''
var scr = document.createElement('script');
scr.type = 'text/javascript';
scr.text = `let calls = (function(){
    let calls = 0;
    let fun = document.createElement;
    document.createElement = function(){
      calls++;
      return fun.apply(document, arguments);
    }
    return ()=>calls;
})();`
document.head.appendChild(scr);
'''
try:
    driver.execute_async_script(execu)
except Exception,e:
    print str(e)

当然,您可以通过selenium
execute\u script
api将
script
标记动态添加到
HEAD
中,请尝试下面的简单代码。如果有效,您可以将
scr.text
更改为您的内容

driver = webdriver.Chrome()
driver.get("http://www.x.org")
// sleep 10 seconds wait page load complete
// you should change to wait in official script
time.sleep(10)

execu = '''
var scr = document.createElement('script');
scr.type = 'text/javascript';
scr.text = 'alert("yes")';
document.head.appendChild(scr);
'''
try:
    driver.execute_script(execu) // if it work, an alert with 'yes' should display

    // sleep for a long time, so that you have more time to 
    // check the script tag appended into head tag or not.
    // only for debug purpose
    time.sleep(30)

except Exception,e:
    print str(e)
请在DevTool的控制台选项卡中逐个执行以下4行:

如果您可以得到一个警报,即在HTML
head
中插入的
script
标记,这意味着javascript片段在您的浏览中工作正常,失败应该来自其他python代码行


脚本将不会添加到页面源中。页面源代码是由
www.x.org
返回的html。因此,您的意思是我无法通过executescript()向页面添加脚本?谢谢,但您的代码与我的代码相同,只是时间不同。sleep()。它不工作,我的意思是它似乎执行成功,但当我查看页面源代码时,脚本不在那里。