Posts

Showing posts with the label python-modules

โหลดไฟล์ด้วย 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 นั่นเอง หึหึหึ

การใช้งาน beautifulsoup สำหรับ python

ใช้ beautifulsoup ทำอะไรได้     เราสามารถใช้โมดูลตัวนี้แกะ dom เพิ่มหรือลบ element ออกจาก dom ได้ ติดตั้ง beautifulsoup >> pip install beautifulsoup4 ลองเล่นกัน >> from bs4 import Beautifulsoup ผมจะลองโหลดหน้าเว็ปจาก google มาดู >> import urllib2 >> p = urllib2.urlopen('http://google.com') >> soup = Beautifulsoup(p) ลอง print ดู ก็จะได้เห้น content เต็มๆ >> print soup ถ้าทำแบบนี้ >> soup.find_all('table') เราก็จะได้ list ของ table ทั้งหมด ใน page นั้น ตัว soup นี้จะมี fn find_*** เยอะมาก อย่างเช่นถ้าเราทำแบบนี้ >> soup.find_all('table')[0] ผลที่ได้ก็จะเป็น element obj ที่เป็นของ bs นั่นเอง ซึ่งเราสามารถเอา attr ออกมาได้โดย >> t0 = soup.find_all('table')[0] >> print t0.attrs >> {'cellpadding': '0', 'cellspacing': '0'} โดยส่วนตัวผมใช้เจ้า bs (Beautifulsoup) ในการแกะเอา link ต่างเพื่อมาใช้โหลดอีกที เพราะว่าผลที่ออกมาจาก code ด้านบ...