[英]Javascript and Selenium: problem with function calls
嗨,我正在尝试自动转到谷歌图像并下载包含上述图像的所有 url 的文件,我有 javascript 代码,我在 chrome 控制台中运行它工作正常,但我不想从 python 使用它。
I tried using Selenium and execute_script, which does work in general however I think there is an issue with using the Javascript function Element.GetBoundingClientRect from Selenium.
在我运行driver.execute_script(script)
后,我在 Chrome 控制台内的 chrome window (Selenium 打开的那个)中观察到,它给了我错误:
Uncaught (in promise) TypeError: Cannot read property 'getBoundingClientRect' of null ...
function 调用在多个位置失败,但最初在:
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 window 读取 position 有关? 如果是这样,我该如何解决这个问题?
谢谢
更新:
function 模拟右击被调用:
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 的控制台中尝试过,似乎 select 所有图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.