Selenium: Upload file in Google Chrome

后端 未结 3 1252
抹茶落季
抹茶落季 2021-01-05 00:42

Is there any way to upload file in Google Chrome since Selenium RC \"attach_file\" only supports *Firefox? Any suggestion or workarounds are much appreciated.

3条回答
  •  伪装坚强ぢ
    2021-01-05 01:28

    Uploading file is usually a POST request, so you actually can upload a file without using Selenium; Unless your site requires cookies, then you need to reconstruct the cookies with webdriver.get_cookies() first

    A simple example:

    # required package:
    #   http://pypi.python.org/pypi/MultipartPostHandler/0.1.0
    
    import MultipartPostHandler, urllib2, cookielib
    
    cookies = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),
                                  MultipartPostHandler.MultipartPostHandler)
    
    path_to_file = r"abc.zip"
    
    open_file = open(path_to_file,"rb")
    param = { "file": open_file }
    req = opener.open("http://www.yoursite.com/uploadfile", param)
    open_file.close()
    

提交回复
热议问题