over 7 years ago

延續之前抓取 http://blog.marsw.tw 網頁的例子,以下示範抓取該網頁其中一篇內文

[程式碼]

06_parsing_html.py
# encoding: utf-8

import urllib2
from lxml import etree

from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    try:
        s = MLStripper()
        s.feed(html)
        return s.get_data()
    except:
        return html

request = urllib2.Request("http://blog.marsw.tw/2013/04/blog-post_9395.html")
response = urllib2.urlopen(request)
html = response.read()

page = etree.HTML(html)

fileout1 = file('06_v1.txt','w')
fileout1.write(("".join(page.xpath(u"//div[@class='post-body entry-content']/descendant::text()"))).encode('utf8'))
fileout1.close()

fileout2 = file('06_v2.txt','w')
fileout2.write(("".join(page.xpath(u"//div[contains(@class, 'post-body')]/descendant::text()"))).encode('utf8'))
fileout2.close()

raw_html = etree.tostring(page.xpath(u"//div[contains(@class, 'post-body')]")[0], pretty_print=True,encoding='UTF-8')
text = strip_tags(raw_html)
fileout3 = file('06_v3.txt','w')
fileout3.write(text)
fileout3.close()

[程式說明]

我們觀察部落格文章的格式,發覺內文是包在div中,
v1的寫法是把完整class的value寫出來,而v2的寫法只要寫class其中一個value
v1、v2的寫法都是利用XPath Axes的概念將article底下不管幾階(descendant)所有的文字印出
而v3的寫法則是將article這個標籤所包含的所有原始html以raw_html這個變數儲存
再以strip_tags函式將raw_html中所有的html標籤去除,以text來儲存並輸出

爬蟲系列教學文目錄
爬蟲系列教學文程式碼
安裝Python及Python常用語法可參考 Python - 十分鐘入門

← [爬蟲] Parsing -抓取網頁標題 & XPath Axes說明(lxml) [爬蟲] lxml、XPath 常用語法 →
 
comments powered by Disqus