2014-04-06 40 views
0

我想使用一個像美麗湯(python)的HTML解析器來獲取特定div的內容,通過運行一個python腳本將其中的所有數據存儲在我的本地服務器中將通過cron定期在我的web服務器上執行。使用HTML解析器獲取特定div的內容

此外,我需要能夠顯示那些內容完全符合他們在我的網站上以前的網頁顯示。

如果div的內容是單獨的文本,它會很容易,但它是文本和圖像的組合。 雖然偶爾會有swf文件,但我不想導入它們。

假設有問題的div被稱爲'cont'。 什麼是最好的方法來做到這一點?

+0

最好的辦法是先寫一些代碼,tbh。否則,你要求的是太寬泛。 – Manhattan

+0

寫完這個問題之後,我認爲XML可能是一種解決這個問題的方法。你認爲這是一個好主意嗎? – dK3

+0

確實有可能。儘管如此,如果頁面被分析的很小,我不明白爲什麼urllib和bs4或lxml的簡單組合不夠用。您也可以將圖像保存爲離線圖像,也可以保存在數據庫中,其中Python已經擁有豐富的資源。 :) – Manhattan

回答

1

幸運的是,我有一隻蜘蛛,它完全符合你的需求。

from soup import BeautifulSoup as bs 
from scrapy.http import Request 
from scrapy.spider import BaseSpider 
from hn.items import HnItem 


class HnSpider(BaseSpider): 
    name = 'hn' 
    allowed_domains = [] 
    start_urls = ['http://news.ycombinator.com'] 

    def parse(self, response): 
     if 'news.ycombinator.com' in response.url: 
      soup = bs(response.body) 
      items = [(x[0].text, x[0].get('href')) for x in 
        filter(None, [ 
         x.findChildren() for x in 
         soup.findAll('td', {'class': 'title'}) 
        ])] 

      for item in items: 
       print item 
       hn_item = HnItem() 
       hn_item['title'] = item[0] 
       hn_item['link'] = item[1] 
       try: 
        yield Request(item[1], callback=self.parse) 
       except ValueError: 
        yield Request('http://news.ycombinator.com/' + item[1], callback=self.parse) 

       yield hn_item 

請參考Github link瞭解更多。

+0

這太棒了!謝謝您的幫助 :) – dK3