cURL là một công cụ được sử dụng để truyền dữ liệu đến và từ một máy chủ và để thực hiện các loại yêu cầu dữ liệu khác nhau. Trong bài viết này mình sẽ giới thiệu về PycURL – một thư viện cURL rất tốt của Python.
- Website: //pycurl.io
- GitHub: //github.com/pycurl/pycurl
Cài đặt PycURL
Để cài đặt thư viện PycURL trong python chúng ta sử dụng công cụ quản lý PIP
pip install pycurl
Nếu bạn gặp phải lỗi: error: command ‘x86_64-linux-gnu-gcc’ failed with exit status 1, thì tham khảo bài viết này để fix lỗi.
Sử dụng PycURL
Một ví dụ sử dụng PycURL
Lấy nội dung website sử dụng PycULR
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import sys import pycurl PY3 = sys.version_info[0] > 2 class Test: def __init__[self]: self.contents = '' if PY3: self.contents = self.contents.encode['ascii'] def body_callback[self, buf]: self.contents = self.contents + buf sys.stderr.write["Testing %s\n" % pycurl.version] t = Test[] c = pycurl.Curl[] c.setopt[c.URL, '//vinasupport.com'] c.setopt[c.WRITEFUNCTION, t.body_callback] c.perform[] c.close[] print[t.contents]
Upload file với PycURL
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import os, sys import pycurl # Class which holds a file reference and the read callback class FileReader: def __init__[self, fp]: self.fp = fp def read_callback[self, size]: return self.fp.read[size] # Check commandline arguments if len[sys.argv] < 3: print["Usage: %s " % sys.argv[0]] raise SystemExit url = sys.argv[1] filename = sys.argv[2] if not os.path.exists[filename]: print["Error: the file '%s' does not exist" % filename] raise SystemExit # Initialize pycurl c = pycurl.Curl[] c.setopt[pycurl.URL, url] c.setopt[pycurl.UPLOAD, 1] # Two versions with the same semantics here, but the filereader version # is useful when you have to process the data which is read before returning if 1: c.setopt[pycurl.READFUNCTION, FileReader[open[filename, 'rb']].read_callback] else: c.setopt[pycurl.READFUNCTION, open[filename, 'rb'].read] # Set size of file to be uploaded. filesize = os.path.getsize[filename] c.setopt[pycurl.INFILESIZE, filesize] # Start transfer print['Uploading file %s to url %s' % [filename, url]] c.perform[] c.close[]
Post form với PyCURL
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import pycurl try: # python 3 from urllib.parse import urlencode except ImportError: # python 2 from urllib import urlencode c = pycurl.Curl[] c.setopt[c.URL, '//httpbin.org/post'] post_data = {'field': 'value'} # Form data must be provided already urlencoded. postfields = urlencode[post_data] # Sets request method to POST, # Content-Type header to application/x-www-form-urlencoded # and data to send in request body. c.setopt[c.POSTFIELDS, postfields] c.perform[] c.close[]
Và rất nhiều ví dụ khác, các bạn vui lòng tham khảo ở đây
Nguồn: vinasupport.com
Để download file từ 1 trang web bất kỳ chúng ta có rất nhiều cách. Sau đây vinasupport.com sẽ hướng dẫn các bạn download file ảnh, video, … từ 1 website bất kỳ về máy tính Linux sử dụng curl command line.
Kiểm tra thông tin của file download
Trước khi download bạn có thể kiểm tra thông tin của file download như:
curl -I //vinasupport.com/assets/img/vinasupport_logo.png
Kết quả:
Hoặc chỉ mã status code
curl -s -I -w "%{http_code}" //vinasupport.com/assets/img/vinasupport_logo.png -o /dev/null
Với:
- 200: File hoạt động bình thường
- 404: File không tồn tại
- …
Download file với curl command
Sử dụng command sau để download 1 file
curl --output
VD:
curl //vinasupport.com/assets/img/vinasupport_logo.png --output vinasupport.png
Sử dụng option:
- –silent: để ko show output [stdout]
Nguồn: vinasupport.com
Bạn có thể download file [File ảnh, File text, …] từ 1 đường dẫn trên web sử dụng thư viện urllib của Python 3.
Đoạn source code Python 3 như sau:
import urllib import os output_dir = '/tmp' image_url = '//vinasupport.com/assets/img/vinasupport_logo.png' # Make output directory if not exist if not os.path.exists[output_dir]: os.makedirs[output_dir] # save path image_save_path = output_dir + '/' + os.path.basename[image_url] # Download file from url urllib.request.urlretrieve[image, image_save_path] print[image_save_path]
Trong ví dụ trên, mình thực hiện download file ảnh có đường dẫn là: //vinasupport.com/assets/img/vinasupport_logo.png
Và lưu nó xuống dường dẫn trên server /tmp/vinasupport_logo.png
Một cách khác là sử dụng thư viện requests
Đầu tiên cài đặt requests thông qua trình quản lý module / packages của Python 3
pip install requests
Sử dụng requests để download file:
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import sys import pycurl PY3 = sys.version_info[0] > 2 class Test: def __init__[self]: self.contents = '' if PY3: self.contents = self.contents.encode['ascii'] def body_callback[self, buf]: self.contents = self.contents + buf sys.stderr.write["Testing %s\n" % pycurl.version] t = Test[] c = pycurl.Curl[] c.setopt[c.URL, '//vinasupport.com'] c.setopt[c.WRITEFUNCTION, t.body_callback] c.perform[] c.close[] print[t.contents]0
Nguồn: vinasupport.com
Bạn có thể download file [File ảnh, File text, …] từ 1 đường dẫn trên web sử dụng thư viện urllib của Python 3.
Đoạn source code Python 3 như sau:
Trong ví dụ trên, mình thực hiện download file ảnh có đường dẫn là: //vinasupport.com/assets/img/vinasupport_logo.png
Và lưu nó xuống dường dẫn trên server /tmp/vinasupport_logo.png
1]
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import sys import pycurl PY3 = sys.version_info[0] > 2 class Test: def __init__[self]: self.contents = '' if PY3: self.contents = self.contents.encode['ascii'] def body_callback[self, buf]: self.contents = self.contents + buf sys.stderr.write["Testing %s\n" % pycurl.version] t = Test[] c = pycurl.Curl[] c.setopt[c.URL, '//vinasupport.com'] c.setopt[c.WRITEFUNCTION, t.body_callback] c.perform[] c.close[] print[t.contents]1
Một cách khác là sử dụng thư viện requests
- I write a txt file with a list of curl command line by line and then:
#! /usr/bin/env python # -*- coding: utf-8 -*- # vi:ts=4:et import sys import pycurl PY3 = sys.version_info[0] > 2 class Test: def __init__[self]: self.contents = '' if PY3: self.contents = self.contents.encode['ascii'] def body_callback[self, buf]: self.contents = self.contents + buf sys.stderr.write["Testing %s\n" % pycurl.version] t = Test[] c = pycurl.Curl[] c.setopt[c.URL, '//vinasupport.com'] c.setopt[c.WRITEFUNCTION, t.body_callback] c.perform[] c.close[] print[t.contents]2
but don't work fine and i have the same output of case 1 above. Now i try to use urllib.request but i'm not able to use it very well.
Someone have a suggestion? Thanks in advance for your help