ตัวอย่างการใช้ python ดูดเว็บ

​อยาก​อ่าน​ข่าว​​ใน​เว็บข่าว​หลาย​​เว็บ

​แต่​เว็บข่าว​​ใน​ไทยหลาย​​เว็บ support rss ​แต่​ไม่ ​ได้​เป็น​แบบ full feed ก็​​เรา​อยาก​ดูดข่าว​มาอ่าน​​ในมือถือ ด้วย​ plucker นิหว่า

ทำ​​ไงดี ​เขียน​​ไพทอน ดูด feed มา​แล้วทำ​การ​โหลด​เว็บ จาก​ลิงค์​​ใน feed พร้อมทั้ง ตัด​แต่​เนื้อหาออกมา สร้าง​เป็น​ไฟล์​ html​ใหม่ ดีกว่า

  • ที่​เขียน​นี้ดูดข่าว​จาก​​เว็บ ผู้จัดการ ข่าว​สด ​เดลินิวส์​ ประ​ชา​ไทย ​เฉพาะ​บางหัวข้อ ที่ผมสน​ใจ
  • ที่​เขียน​นี้ feed ถ้า error จะ​ try ​ไป​เรื่อย ๆ​
  • ​เข้ารหัสตัวอักษร​ใหม่ ​เป็น ​แบบ tis620

import feedparser
import urllib2
import socket
import re
def strip_html_tags(value):
    return re.sub(r'<[^>]*?>', '', value)
timeout = 6
ListWebs = [{"allurl":["http://www.prachatai.com/rss/"],"webencoding":"tis620","feedencoding":"tis620","beginBody":'<td align="left"><br>',"endBody":'<table width="100%"  border="0" cellspacing="0" cellpadding="0">',"endHead":'</div>'},
{"allurl":["http://www.matichon.co.th/khaosod/rss/politics_news.xml","http://www.matichon.co.th/khaosod/rss/foreign_news.xml","http://www.matichon.co.th/khaosod/rss/economy_news.xml","http://www.matichon.co.th/khaosod/rss/motor_news.xml","http://www.matichon.co.th/khaosod/rss/technology_news.xml"],"webencoding":"tis620","feedencoding":"utf8","beginBody":'<td align=left valign=top><font face=Tahoma, MS Sans Serif, CordiaUPC, DB ThaiText Extra, Thonburi size=3>',"endBody":'</td></tr></table>',"beginHead":'<div class="topic4">',"endHead":'</div>'},
{"allurl":["http://www.manager.co.th/RSS/Around/Around.xml","http://www.manager.co.th/RSS/China/China.xml","http://www.manager.co.th/RSS/Business/Business.xml  ","http://www.manager.co.th/RSS/StockMarket/StockMarket.xml","http://www.manager.co.th/RSS/Motoring/Motoring.xml","http://www.manager.co.th/RSS/Cyberbiz/Cyberbiz.xml","http://www.manager.co.th/RSS/Science/Science.xml"],"webencoding":"tis620","beginBody":'<td align="left" valign="baseline" class="body">\r\n',"endBody":'\r\n</td>\r\n</tr>\r\n</table>',"beginHead":'<td align="left" valign="baseline" class="headline">',"endHead":'</td>'},
{"allurl":["http://ads.dailynews.co.th/rss/1.xml","http://ads.dailynews.co.th/rss/2.xml","http://ads.dailynews.co.th/rss/5.xml","http://ads.dailynews.co.th/rss/6.xml","http://ads.dailynews.co.th/rss/8.xml"],"webencoding":"utf8","feedencoding":"utf8","beginBody":'<div id="news_detail" >',"endBody":'</table>\r\n</div>',"beginHead":'<div class="topic4">',"endHead":'</div>'},
]
socket.setdefaulttimeout(timeout)
indexFile = open("index.html","w")
indexFile.write("<html><head><title>news_now</title></head>\n<body>\n")
itemIndex = 0
for web in ListWebs:
    allurl = web["allurl"]
    webencoding = web["webencoding"]
    beginBody = web["beginBody"]
    endBody = web["endBody"]
    for url in allurl:
        numtry = 0
        wetry=1
        while numtry<100 or wetry!=0:
            numtry = numtry+1
            wetry=0
            try:
                d = feedparser.parse(url)
                title = d.feed.title
            except:
                wetry=1
                print "feederror",url
        oldDate = (2006, 9, 4, 12, 57, 14, 3, 248, 0)
        indexFile.write("<h1>"+title.encode("tis620","ignore")+"</h1><br>\n")
        nencoding = d.encoding
        print title.encode("tis620","ignore")
        for item in d.entries:
            itemIndex = itemIndex+1
            DateItem = item.updated_parsed
            urlItem = item.link
            itemTitle = item.title
            itemTitle = itemTitle.encode("tis620","ignore")
            req = urllib2.Request(urlItem)
            wetry=1
            numtry=0
            while wetry!=0 or numtry > 100:
                try:
                    numtry = numtry+1
                    itemRawData = urllib2.urlopen(req)
                    itemTextData = itemRawData.read()
                    wetry = 0
                except IOError, e:
                    print numtry,"url",urlItem
                    wetry =1
                    if hasattr(e, 'reason'):
                        print 'Reason: ', e.reason
                    elif hasattr(e, 'code'):
                        print 'Error code: ', e.code
                except:
                    print numtry,"url",urlItem
                    wetry =1
            itemBegin = itemTextData.find(beginBody)
            itemEnd = itemTextData.find(endBody,itemBegin)
            itemTextData = itemTextData[itemBegin:itemEnd]
            itemTextData = itemTextData.replace(" "," ");
            stag = strip_html_tags(itemTitle)
            indexFile.write('<a href="'+str(itemIndex)+'.html">'+stag+'</a><br>\n')
            stag2=strip_html_tags(itemTextData)
            stag2 = stag2.decode(webencoding,"ignore")
            dataFile = open(str(itemIndex)+".html","w")
            dataFile.write("<html><head><title>"+stag+"</title></head>\n<body>")
            dataFile.write("<h1>"+stag+"</h1><br>\n")
            dataFile.write(stag2.encode("tis620","ignore"))
            dataFile.write("</body></html>")
            dataFile.close()
            print stag
            indexFile.close()
            indexFile = open("index.html","a")
indexFile.write("</body></html>")
indexFile.close()

  • ยัง​อยาก​ปรับปรุง​ให้​เป้น multi thread ​อยู่
  • package feed parser ตั้งค่า timeout ตรง​ไหนฟะ​u
  • ระ​วัง​เรื่อง string encoding ​เพราะ​ feedparser ​ได้​แอบ​ใช้ package ชื่อ chardet ​ในการระ​บุ encoding ถ้า​ไม่มี มันจะ​ระ​บุ​เป็น utf8 ​​อย่างมั่ว ๆ​
3.8
Your rating: None Average: 3.8 (5 votes)