request python まとめ

what is request

requestsとはサードパーティ製のhttp通信を行うためのライブラリ これを使用すると、webサイトのデータのダウンロードやrestapiの使用が可能 install cmd pip install requests

example

ヤフーのニュース一覧ページのhtmlを取得 import requests url = "https://news.yahoo.co.jp/topics" r = requests.get(url) print(r.text)

urlから画像ダウンロード

import urllib.error import urllib.request headers = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0", }

def download_image(url, dst_path, headers): try: # request = urllib.request.Request(url=url, headers=headers) # data = urllib.request.urlopen(request)

    data = urllib.request.urlopen(url,headers).read()
    with open(dst_path, mode="wb") as f:
        f.write(data)
except urllib.error.URLError as e:
    print(e)

url = 'URL' dst_path = 'lena_square.png'

dst_dir = 'data/src'

dst_path = os.path.join(dst_dir, os.path.basename(url))

download_image(url, dst_path, headers)

urlからhtmlコンテンツダウンロード

coding:utf-8

import urllib.request

url = "URL" headers = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0", }

request = urllib.request.Request(url=url, headers=headers) response = urllib.request.urlopen(request) html = response.read().decode('utf-8') print(html)

参考

http://www.python.ambitious-engineer.com/archives/974#requests