[英]Returning javascript data from Python Selenium Web Driver
I'm trying to run a javascript file inside a Python file using Selenium WebDriver and get the return value from the javascript function. 下面的尝试应该可以从我在网上查到的内容进行。 我已经为此工作了几个小时,但无济于事。 任何帮助,将不胜感激。
Python 代码:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import os
driver = webdriver.Chrome(executable_path='chromedriver')
driver.get('example.com')
# Clean up the text inside the <p> tags
js_file = 'clean_text.js'
with open(js_file, 'r') as f:
script = f.read()
# Attempt 1
text = driver.execute_script(script)
# Attempt 2
text = driver.execute_script(f'return {script}')
# Attempt 3
text = WebDriverWait(driver, 20).until(lambda driver: driver.execute_script(script))
# Attempt 4
text = WebDriverWait(driver, 20).until(lambda driver: driver.execute_script(f'return {script}'))
尝试返回 None 或 selenium.common.exceptions.TimeoutException
Javascript 代码:
$(document).ready(function() {
// Collect the text within the nested <p> tags
var text = [];
// get all nested <p> tags
let paragraphs = $(`div#id div[data-test-id=value] p`);
// Replace all whitespaces with a single white space
paragraphs.each(function(index) {
let original_text = $(this).text();
let cleaned_text = original_text.trim().replace(/\s\s+/g, ' ');
$(this).text(cleaned_text);
text.push(cleaned_text);
});
return text;
});
鉴于此 JS 代码下方的 furas 答案适用于尝试 1 和 4。我需要在开头添加“return”,“();” 最后并移除 jQuery。
return function cleanText() {
// Collect the text within the nested <p> tags
var text = [];
// get all nested <p> tags
let paragraphs = $(`div#id div[data-test-id=value] p`);
// Replace all whitespaces with a single white space
paragraphs.each(function(index) {
let original_text = $(this).text();
let cleaned_text = original_text.trim().replace(/\s\s+/g, ' ');
$(this).text(cleaned_text);
text.push(cleaned_text);
});
return text;
}();
所有问题都可能是因为您在ready()
中运行function()
) 并且它return
将text
发送到ready()
,而不是发送给您。 您必须直接运行function
才能获得结果。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import os
import time
driver = webdriver.Chrome()# executable_path='chromedriver')
driver.get('http://quotes.toscrape.com/js/')
#script = '$(document).ready(function() { return "Hello World"; })';
script = 'function test() { return "Hello World"; })()';
time.sleep(3)
# Attempt 1
text = driver.execute_script(script)
print(text) # None
# Attempt 2
text = driver.execute_script(f'return {script}')
print(text) # Hello World
# Attempt 3
#text = WebDriverWait(driver, 20).until(lambda driver: driver.execute_script(script))
#print(text) # error
# Attempt 4
text = WebDriverWait(driver, 20).until(lambda driver: driver.execute_script(f'return {script}'))
print(text) # Hello World
编辑:
如果你真的需要检查文件是否准备好,那么你应该在你的 function 里面做。 您可以尝试使用带有变量$.isReady
的while
-loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.