简体   繁体   中英

Save unicode text from response without encoding into file

I want to download config file from my router via web scraping. The procedure I want to achieve is this:

  1. Save the config file into disk
  2. Send a factory reset
  3. Load the config file previously downloaded.

So far, I have this code:

with requests.Session() as s:  # To login into the modem
    pagePostBackUp = 'https://192.168.1.1/goform/BackUp'
    s.post(urlLogin, data=loginCredentials, verify=False, timeout=5)
    dataBackUp = {'dir': 'admin/','file': 'cmconfig.cfg'}
    resultBackUp = s.post(pagePostBackUp, data=dataBackUp, verify=False, timeout=10)
    print(resultBackUp.text)

The last line is what I want to save into a file. But, when I try to do it with this code:

f = open('/Users/user/Desktop/file.cfg', 'w')

Throws an error that ascii codec can't encode character. If I save the file with, for example, encode='utf16', differs from what I originally download manually.

So, the question is, How can I save this file with the same encoding the router gives me via web? (As unicode). The content of the file looks like this:

g m Z ? ofpqJ U\\V,.o / zf v ~W3=, D};y tL cJ

Change the last line of your code to the following:

    with open('/Users/user/Desktop/file.cfg', 'wb') as f:
        f.write(resultBackUp.content)

This will treat the payload as data ( bytes ), not text: the file is opened in binary mode, and the content is taken as-is. There's no encoding/decoding happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM