如何将jQuery与硒execute_script方法一起使用? [英] How can I use jQuery with selenium execute_script method?

查看:228
本文介绍了如何将jQuery与硒execute_script方法一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果当前页面尚未使用jQuery,如何将jQuery与硒execute_script方法一起使用?

How can I use jQuery with the selenium execute_script method, if the current page isn't already using jQuery?

例如:

from selenium import webdriver
driver = webdriver.Firefox()
driver.get(url)
driver.execute_script('$("#id").wrap("<h1></h1>")')

我尝试添加如下脚本:

driver.execute_script(
"var jquery_script = document.createElement('script'); 
jquery_script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
document.findElementsByTag('head')[0].appendChild(jquery_script)"
)

但是我收到错误消息,说jquery_script变量未定义.

But I get errors saying that the jquery_script variable is undefined.

推荐答案

加载本地jquery似乎更好:

It seems way better to load a local jquery:

with open('jquery.js', errors='ignore') as f:
  driver.execute_script(f.read())

title = driver.execute_script('return $("title").text()')

速度更快,您不必担心时间问题.

It's faster and you don't have to worry about timing issues.

这篇关于如何将jQuery与硒execute_script方法一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆