我在 Python 3 中使用 Selenium 来获取使用 JavaScript 的站点的页面源。当我在 iPython shell 中以交互方式运行它时,它会按我的预期工作。但是,当以非交互方式执行完全相同的脚本时,页面源不会完全呈现(JavaScript 组件不会被呈现)。这可能是什么原因?我在完全相同的机器(无头 Linux 服务器)上运行完全相同的代码。
#!/usr/bin/python3
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
WINDOW_SIZE = "1920,1080"
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size={0}".format(WINDOW_SIZE))
chrome_options.add_argument("--no-sandbox")
service = Service('/usr/local/bin/chromedriver')
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.get("https://www.stakingrewards.com/staking/?page=1&sort=rank_ASC")
src = driver.page_source
# Check page source length
print(len(src))
# Quit all windows related to the driver instance
driver.quit()
iPython shell 的输出220101是预期的,而命令行执行脚本 ( $ python script.py) 的输出是38265. 因此,当我从命令行调用脚本时,我没有有效地呈现 JavaScript 组件。为什么?!