Get the latest jetpack plugin

Page content

http://sosa0sa.com:2368/use-jetpack-for-wordpress-5-0/ 의 연장선. Jetpack plugin의 최신 버전을 알아내서 자동으로 해당 바이너리 파일을 다운로드 받아 보자.

몇 가지 module 을 사용하는데 필요한 module은 https://realpython.com/python-web-scraping-practical-introduction/ 을 참고해서 설치

$ python3 -m venv venv
$ . ./venv/bin/activate
$ pip3 install requests BeautifulSoup4

webscrap.py

from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
from urllib.request import *

'''
https://realpython.com/python-web-scraping-practical-introduction/
'''

def simple_get(url):
    """
    Attempts to get the content at `url` by making an HTTP GET request.
    If the content-type of response is some kind of HTML/XML, return the
    text content, otherwise return None.
    """
    try:
        with closing(get(url, stream=True)) as resp:
            if is_good_response(resp):
                return resp.content
            else:
                return None

    except RequestException as e:
        log_error('Error during requests to {0} : {1}'.format(url, str(e)))
        return None


def is_good_response(resp):
    """
    Returns True if the response seems to be HTML, False otherwise.
    """
    content_type = resp.headers['Content-Type'].lower()
    return (resp.status_code == 200
            and content_type is not None
            and content_type.find('html') > -1)


def log_error(e):
    """
    It is always a good idea to log errors.
    This function just prints them, but you can
    make it do anything.
    """
    print(e)

def download_file(base_url, filename):
	file_url = '%s/%s' %(base_url, filename)

	print("Download %s" %(file_url))
        
	try:
		from tqdm import tqdm
	except:
		urlretrieve(file_url, filename)
		return

	# use tqdm to display the progress but too slow
	file_response = get(file_url, stream=True)
	with open(filename, 'wb') as handle:
		for data in tqdm(file_response.iter_content()):
			handle.write(data)

Jetpack plugin 페이지에 있는 버전 정보를 이용해서 플러그인 다운로드 하기 tqdm은 progress를 보여주는 모듈인데 그냥 사용하면 속도가 너무 너무 느리다. 몇 초면 다운 받을 수 있는 파일을 1분에 걸쳐 받는…

get_jetpack.py

from webscrap import *

'''
https://realpython.com/python-web-scraping-practical-introduction/
https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python
'''

if __name__ == '__main__':
    jetpack_url='https://wordpress.org/plugins/jetpack/'
    jetpack_ver = None

    response = simple_get(jetpack_url)

    if response is not None:
        html = BeautifulSoup(response, 'html.parser')

        for i,l1 in enumerate(html.select('li')):
            if l1.text.strip().find("Version:") == 0:
                jetpack_ver = l1.text.strip().split()[1]
                break

        if jetpack_ver is not None:
            filename = 'jetpack.%s.zip' %jetpack_ver
            download_file(jetpack_url, filename)