首页 > 解决方案 > Python Selenium:使用 javascript:__dopostback 的下载方法不适用于所有网站

问题描述

我尝试在 Python 中使用 selenium 技术和 google chrome/chrome 驱动程序在 url 处下载文件:

  1. https://tso.nbpower.com/Public/en/system_information_archive.aspx(点击“获取数据”按钮时下载文件)。在检查按钮时,我们可以看到它后面是启动的 « javascript__dopostback » 命令。
  2. 我还尝试通过以下链接下载文件:https ://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type=0&season=2020&month=0&season1=2020&ind=0&team=0&rost=0&age= 0&filter=&players=0&startdate=2020-01-01&enddate=2020-12-31 有一个«导出数据»按钮,后面有相同的«javascript__dopostback»命令。

在使用完全相同的代码时,它在网站 1 中不起作用。有人知道我错过了什么吗?

这是代码:

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

from webdriver_manager.chrome import ChromeDriverManager

from selenium.webdriver.support.ui import Select

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import time


from selenium.common.exceptions import WebDriverException   

def main():

    options = Options()
    options.headless = True

    driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)

    driver.get("https://tso.nbpower.com/Public/en/system_information_archive.aspx")
    # driver.get("https://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type=0&season=2020&month=0&season1=2020&ind=0&team=0&rost=0&age=0&filter=&players=0&startdate=2020-01-01&enddate=2020-12-31")
    # Above in comments url of the 2nd website (working)

    driver.implicitly_wait(10)

    xpath = '//*[@id="ctl00_cphMainContent_lbGetData"]'
    # xpath = '//*[@id="LeaderBoard1_cmdCSV"]'
    # Above in comments xpath of the 2nd website button to download file (working)

    button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, xpath)))
    print(button)
    print(button.is_enabled())
    print(button.is_displayed())
    print(button.is_selected())
    test = button.click()

    driver.close()




if __name__ == '__main__':
    main()

附加信息:Google Chrome 88.0.4324.150 与兼容的 Chromedriver 一起使用;操作系统是没有图形界面的Linux。

标签: pythonseleniumselenium-webdriverselenium-chromedriverdom-events

解决方案


推荐阅读