爬蟲之JSON案例

來源:互聯網
上載者:User

標籤:port   com   like   webkit   提取   json   頁面   htm   效果   

糗事百科執行個體:

爬取糗事百科段子,假設頁面的URL是 http://www.qiushibaike.com/8hr/page/1

要求:
  1. 使用requests擷取頁面資訊,用XPath / re 做資料提取

  2. 擷取每個文章裡的帳戶圖片連結使用者姓名段子內容點贊次數評論次數

  3. 儲存到 json 檔案內

參考代碼
#qiushibaike.py#import urllib#import re#import chardetimport requestsfrom lxml import etreepage = 1url = ‘http://www.qiushibaike.com/8hr/page/‘ + str(page) headers = {    ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36‘,    ‘Accept-Language‘: ‘zh-CN,zh;q=0.8‘}try:    response = requests.get(url, headers=headers)    resHtml = response.text    html = etree.HTML(resHtml)    result = html.xpath(‘//div[contains(@id,"qiushi_tag")]‘)    for site in result:        item = {}        imgUrl = site.xpath(‘./div/a/img/@src‘)[0].encode(‘utf-8‘)        username = site.xpath(‘./div/a/@title‘)[0].encode(‘utf-8‘)        #username = site.xpath(‘.//h2‘)[0].text        content = site.xpath(‘.//div[@class="content"]/span‘)[0].text.strip().encode(‘utf-8‘)        # 投票次數        vote = site.xpath(‘.//i‘)[0].text        #print site.xpath(‘.//*[@class="number"]‘)[0].text        # 評論資訊        comments = site.xpath(‘.//i‘)[1].text        print imgUrl, username, content, vote, commentsexcept Exception, e:    print e
示範效果

 

爬蟲之JSON案例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.