【发布时间】:2026-01-27 18:45:02
【问题描述】:
您好,我正在尝试自动转到 Google 图片并下载包含上述图片所有网址的文件, 我有在 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 );
} );
} );
}
【问题讨论】:
-
你是如何调用
simulateRightClick的?该错误表明element为空或None。 -
@PaulM。它在grabUrls() 函数中被调用:simulateRightClick(element.querySelector(':scope img'));
-
您对
querySelector的调用似乎有时会返回None。如果不知道element是什么,以及它的后代元素是什么样子,很难说它有什么问题。 -
我添加了调用simulateRightClick的函数
标签: javascript python selenium