gpt-4o-mini-2024-07-18· openai
from WildChat-4.8M
give me a simple python script that can download content from webpage
- User
give me a simple python script that can download content from webpage
- Assistant
Certainly! You can use the
requestslibrary in Python to download content from a webpage. Below is a simple script that demonstrates how to do this.Make sure you have the
requestslibrary installed. You can install it using pip if you haven't already:bashpip install requestsHere is the Python script:
pythonimport requests def download_webpage(url): try: # Send a GET request to the specified URL response = requests.get(url) # Check if the request was successful response.raise_for_status() # Save the content to a file with open('webpage_content.html', 'w', encoding='utf-8') as file: file.write(response.text) print("Webpage content downloaded successfully.") except requests.exceptions.RequestException as e: print(f"An error occurred: {e}") if __name__ == "__main__": # Replace the URL with the one you want to download url = 'https://www.example.com' download_webpage(url)How to Use the Script
- Replace
'https://www.example.com'with the desired URL of the webpage you want to download. - Save the script in a
.pyfile, for example,download_webpage.py. - Run the script using Python:
bashpython download_webpage.pyOutput
The content of the webpage will be saved to a file named
webpage_content.htmlin the same directory as the script.Note
- Make sure that you have permission to download and store the content from the website as per its terms of service.
- This script downloads only the HTML content of the webpage. If you need to download associated files (like images, scripts, etc.), you would need to implement additional logic to handle those.
- Replace