javascript - Javascript 和 Selenium:函数调用的问题
问题描述
嗨,我正在尝试自动转到谷歌图像并下载包含上述图像的所有 url 的文件,我有在 chrome 控制台中运行的 javascript 代码,它工作正常,但我不想从 python 中使用它。
我尝试使用 Selenium 和 execute_script,这通常可以正常工作,但是我认为使用 Selenium 的 Javascript 函数 Element.GetBoundingClientRect 存在问题。
运行后,我driver.execute_script(script)
在 Chrome 控制台内的 chrome 窗口(Selenium 打开的窗口)中观察到,它给了我错误:
Uncaught (in promise) TypeError: Cannot read property 'getBoundingClientRect' of null ...
函数调用在多个位置失败,但最初在:
function simulateRightClick( element ) {
var event1 = new MouseEvent( 'mousedown', {
bubbles: true,
cancelable: false,
view: window,
button: 2,
buttons: 2,
clientX: element.getBoundingClientRect().x,
clientY: element.getBoundingClientRect().y
} );
element.dispatchEvent( event1 );
var event2 = new MouseEvent( 'mouseup', {
bubbles: true,
cancelable: false,
view: window,
button: 2,
buttons: 0,
clientX: element.getBoundingClientRect().x,
clientY: element.getBoundingClientRect().y
} );
element.dispatchEvent( event2 );
var event3 = new MouseEvent( 'contextmenu', {
bubbles: true,
cancelable: false,
view: window,
button: 2,
buttons: 0,
clientX: element.getBoundingClientRect().x,
clientY: element.getBoundingClientRect().y
} );
element.dispatchEvent( event3 );
}
问题与无法从 Selenium chrome 窗口读取位置有关吗?如果是这样,我该如何解决这个问题?
谢谢
更新:
函数simulateRightClick在以下位置被调用:
function grabUrls() {
var urls = [];
return new Promise( function( resolve, reject ) {
var count = document.querySelectorAll(
'.isv-r a:first-of-type' ).length,
index = 0;
Array.prototype.forEach.call( document.querySelectorAll(
'.isv-r a:first-of-type' ), function( element ) {
// using the right click menu Google will generate the
// full-size URL; won't work in Internet Explorer
// (http://pyimg.co/byukr)
simulateRightClick( element.querySelector( ':scope img' ) );
// Wait for it to appear on the <a> element
var interval = setInterval( function() {
if ( element.href.trim() !== '' ) {
clearInterval( interval );
// extract the full-size version of the image
let googleUrl = element.href.replace( /.*(\?)/, '$1' ),
fullImageUrl = decodeURIComponent(
getURLParam( googleUrl, 'imgurl' ) );
if ( fullImageUrl !== 'false' ) {
urls.push( fullImageUrl );
}
// sometimes the URL returns a "false" string and
// we still want to count those so our Promise
// resolves
index++;
if ( index == ( count - 1 ) ) {
resolve( urls );
}
}
}, 10 );
} );
} );
}
解决方案
感谢您更新您的帖子。您的查询对我来说很好 - 不知道出了什么问题。您是否尝试过使查询更简单,像这样?:
Array.prototype.forEach.call( document.querySelectorAll(
".isv-r img:first-of-type" ), function( img ) {
simulateRightClick( img );
...
我刚刚在 Chrome 的控制台中尝试过,它似乎选择了所有图像。
推荐阅读
- c++ - uint8_t 和 unsigned char 之间的混淆
- python - Django - 分配经过身份验证的用户发布(自动)
- javascript - 创建队列时如何解决rsmq队列已经退出错误?
- swift - SwiftUI - 键盘启动后选择时选择器冻结
- powershell - 在 azure devops 管道中使用时间戳变量
- arrays - VBA变量不引用数组
- c++ - 使用 libcurl 将返回的数据存储在 shared_ptr 中
- node.js - 如何在 NextJS Vercel 项目中进行 301 重定向?
- azure - 将 Azure 函数发布到 Azure 随机失败
- php - DB::select 的输出与 phpMyAdmin 中的原始查询不同