Yes, Mechanize can handle both file uploads and downloads. Mechanize is a programmatic web browsing library for Python that can perform most actions that you can perform with a web browser, including sending form data and handling file uploads and downloads. Below, you'll find examples of how to handle file uploads and downloads using Mechanize in Python.
File Uploads with Mechanize
When uploading a file using Mechanize, you need to open the form containing the file input, set the file object to the control, and then submit the form.
Here is a simple example:
import mechanize
# Create a browser object
br = mechanize.Browser()
# Open the page with the form
br.open('http://example.com/upload')
# Select the form that you will interact with by index or name
br.select_form(nr=0)
# Find the file upload field by the control name
file_control = br.form.find_control("file", type="file")
# Set the file object to this control, which should be a tuple
# consisting of (filename, file_data, MIME_type)
file_control.add_file(open('file_to_upload.txt', 'rb'), 'text/plain', 'file_to_upload.txt')
# Submit the form with the file
response = br.submit()
# Optionally, check the response
print(response.read())
Make sure to replace 'http://example.com/upload'
with the URL of the page you want to upload to, and adjust the form control names as necessary.
File Downloads with Mechanize
For downloading files, you can simply open the URL of the file and read the response:
import mechanize
# Create a browser object
br = mechanize.Browser()
# Open the URL of the file you want to download
response = br.open('http://example.com/file_to_download.zip')
# Read the contents of the response
file_data = response.read()
# Write the data to a file
with open('downloaded_file.zip', 'wb') as file:
file.write(file_data)
print('File downloaded successfully.')
Replace 'http://example.com/file_to_download.zip'
with the actual URL of the file you want to download, and 'downloaded_file.zip'
with the desired local filename.
Notes on Mechanize
- Mechanize only works with Python 2.x, and it hasn't been actively maintained for Python 3.x. If you're using Python 3, you might want to consider alternatives like RoboBrowser or MechanicalSoup, which offer similar functionalities.
- For complex JavaScript-driven sites, Mechanize may not be sufficient because it doesn't execute JavaScript. In such cases, you might look into using Selenium or Puppeteer (for Node.js).
Always remember that web scraping and automated interactions with websites should be done responsibly and in compliance with the terms of service and legal restrictions of the website you are interacting with.