[Python] how to handle web scraping error beacuase of its data type

Discussão em 'Python' iniciado por Stack, Março 8, 2025.

  1. Stack

    Stack Membro Participativo

    I'm starting web scraping with python and playwright. but when I run the code I get an error .how to find type of response data(binary,text.ASCI,...) and handle the error about convert and save data as text data in a file.

    from playwright.sync_api import sync_playwright
    import json

    def handle_response(response):
    with open("copy.txt", "w", encoding="utf-8") as file:
    file.write(response.text())



    def main():
    playwright=sync_playwright().start()
    browser=playwright.chromium.launch(headless=True)
    browser.new_context(no_viewport=True)
    page=browser.new_page()
    page.on('response',lambda response:handle_response(response))
    page.goto("https://www.booking.com/hotel/it/hotelnordroma.en-gb.html?aid=304142&checkin=2025-05-15&checkout=2025-05-16#map_opened-map_trigger_header_pin")
    page.wait_for_timeout(1000)
    browser.close()
    playwright.stop()

    if __name__=='__main__':
    main()


    Error:


    Exception has occurred: UnicodeDecodeError 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte File "J:\SeSa\Playwright\sample.py", line 6, in handle_response file.write(response.text()) ~~~~~~~~~~~~~^^ File "J:\SeSa\Playwright\sample.py", line 15, in page.on('response',lambda response:handle_response(response))
    ~~~~~~~~~~~~~~~^^^^^^^^^^ UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
    ​

    Continue reading...

Compartilhe esta Página