利用BeautifulSoup抓取新浪網頁新聞的內容,beautifulsoup抓取

來源:互聯網
上載者:User

利用BeautifulSoup抓取新浪網頁新聞的內容,beautifulsoup抓取

第一次寫的小爬蟲,python確實功能很強大,二十來行的代碼抓取內容並儲存為一個txt文本

直接上代碼

#coding = 'utf-8'import requestsfrom bs4 import BeautifulSoupimport sysreload(sys)sys.setdefaultencoding("utf-8")#抓取web頁面url = "http://news.sina.com.cn/china/"res = requests.get(url)res.encoding = 'utf-8'#放進soup裡面進行網頁內容剖析soup = BeautifulSoup(res.text, "html.parser")elements = soup.select('.news-item')    #抓取需要的內容並且放入檔案中#抓取的內容有時間,內容文本,以及內容的連結fname = "F:/asdf666.txt"try:    f = open(fname, 'w')    for element in elements:        if len(element.select('h2')) > 0:            f.write(element.select('.time')[0].text)            f.write(element.select('h2')[0].text)            f.write(element.select('a')[0]['href'])            f.write('\n\n')        f.close()except Exception, e:    print eelse:    passfinally:    pass

 因為這隻第一次做的小爬蟲,功能很簡單也很單一,就是直接抓取新聞頁面的部分新聞

然後抓取新聞的時間和超連結

然後按照新聞的順序整合起來,並且放進文字檔中去儲存起來

截取一下,效果很簡單,就是一條一條的記錄,時間,新聞內容,新聞連結(因為是今天才寫的,所以新聞都是今天的)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.