Python使用selenium获取JS代码里边的变量值

from selenium import webdriver


driver = webdriver.Ie(r"IEDriverServer.exe")  # 找一个合适版本的IEDriver
js = """
var hello = "hello world";
return hello;
"""
result = driver.execute_script(js)
print(result)
"D:\Program Files\Python36\python3.exe" D:/MyProject/Python/ReturnVisit/test.py
hello world

Process finished with exit code 0

上面这种会打开一个IE浏览器,如果不想让程序打开页面,可以使用谷歌无头浏览器。

下面的代码可以得到与上面相同的输出结果,并且程序不会打开浏览器。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome("chromedriver.exe", chrome_options=chrome_options)
js = """
var hello = "hello world";
return hello;
"""
result = driver.execute_script(js)
print(result)

 

猜你喜欢

转载自blog.csdn.net/TomorrowAndTuture/article/details/103953206