โหลดไฟล์ด้วย urllib2

urllib2 module เป็นตัวที่ผมชอบและใช้อยู่เป็นประจำ นี่เป็น code ที่ผมเขียนเก็บไว้เพื่อใช้กับ code อื่นๆในการเขียน script ที่ใช้โหลดไฟล โดยมาจะใช้โหลดเว็ปการตูนต่างๆ

import urllib2
def download(filename, img_url):
    p = urllib2.urlopen(img_url)
    with open(filename, 'w') as f:
        f.write(p.read())

จิงๆแล้วบางเว็ปอาจจะห้าม user-agent ที่ไม่รู้จักโหลดไฟล ด้วยความสามารถของ urllib2 เราก็จะทำแบบนี้ได้

import urllib2
def download(filename, img_url):
    req = urllib2.Request(img_url, headers={'User-Agent':'Mozilla/5.0'})
    p = urllib2.urlopen(req)
    with open(filename, 'w') as f:
        f.write(p.read())

จะเห็นได้ว่าเราสามารถกำหนด header ได้เองและ
img_url ก็แกะออกมาได้จาก beautifulsoup module นั่นเอง หึหึหึ

Comments

Popular posts from this blog

Difference between apt-get update and apt-get dis-upgrade