爬取知乎Python中文社區資訊

來源:互聯網
上載者:User

標籤:base   try   neu   repos   asc   exce   rom   yield   .json   

 爬取知乎Python中文社區資訊,https://zhuanlan.zhihu.com/zimei

 

 1 import requests 2 from urllib.parse import urlencode 3 from pyquery import PyQuery as pq 4 from pymongo import MongoClient 5 import json 6 import time 7  8 base_url = ‘https://www.zhihu.com/api/v4/columns/zimei/articles?limit=10&‘ 9 headers = {10     ‘authority‘: ‘www.zhihu.com‘,11     ‘referer‘: ‘https://zhuanlan.zhihu.com/zimei‘,12     ‘origin‘: ‘https://zhuanlan.zhihu.com‘,13     ‘User-Agent‘: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36‘,14 }15 16 client = MongoClient()17 db = client[‘zhihu‘]18 collection = db[‘zhihu‘]19 max_page = 10020 21 22 def get_page(page):23     params = {24         ‘offset‘: page*1025     }26     url = base_url + urlencode(params)27     try:28         response = requests.get(url, headers=headers)29         if response.status_code == 200:30 31             return response.json()32     except requests.ConnectionError as e:33         print(‘Error‘, e.args)34 35 36 def parse_page(json_1):37     if json_1:38         items = json_1.get(‘data‘)39         for item in items:40             if page == 1 :41                 continue42             else:43                 44                 zhihu = {}45                 zhihu[‘name‘] = item.get(‘author‘).get(‘name‘)46                 zhihu[‘title‘] = item.get(‘title‘)47                 zhihu[‘text‘] = pq(item.get(‘excerpt‘)).text()48                 zhihu[‘comments‘] = item.get(‘comment_count‘)49                 zhihu[‘reposts‘] = item.get(‘voteup_count‘)50                 zhihu[‘data‘] = time.strftime(‘%Y-%m-%d %H%:%M‘,time.localtime(item.get(‘updated‘)))51                 yield zhihu52 53 def write_to_file(content):54     with open(‘zhihu.json‘,‘a‘,encoding=‘utf-8‘) as f:55         f.write(json.dumps(content,ensure_ascii=False)+‘\n‘)56         f.close()57 58 def save_to_mongo(result):59     if collection.insert(result):60         print(‘Saved to Mongo‘)61 62 63 if __name__ == ‘__main__‘:64     for page in range(1, max_page + 1):65         json_1 = get_page(page)66 67         results = parse_page(json_1)68         for result in results:69             print(result)70             write_to_file(result)71             save_to_mongo(result)

 

 

爬取知乎Python中文社區資訊

相關文章

聯繫我們

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