简单爬取知乎热榜到mongodb

import pymongo
import requests
from requests.exceptions import ConnectionError
from pyquery import PyQuery as pq

client = pymongo.MongoClient('localhost')
db = client['zhihu']



base_url = 'https://www.zhihu.com/hot'

headers = {
        'Cookie':'_c10c',
        'Host':'www.zhihu.com',
        'Upgrade-Insecure-Requests':'1',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
        }


def get_html(url):
    try:
        response =requests.get(url,allow_redirects=False,headers=headers)
        if response.status_code == 200:
            return response.text
            print('200')
        if response.status_code == 302:
            print('302')
        if response.status_code == 404:
            print('404')
        
    except ConnectionError:
        return get_html(url)
        
def save_mongo(data):
    if db['hot'].update({'title':data['title']},{'$set':data},True):
        print('save to mongo',data['title'])
    else:
        print('failed',data['title'])

def get_index():
    url = base_url
    html = get_html(url)
    doc = pq(html)
    title = doc('.HotItem-title').items()
    hot = doc('.HotItem-metrics.HotItem-metrics--bottom').items()
    href = doc('.HotItem-content a').items()

    for o,i,e in zip(title,hot,href):
        dic1 = {}
        dic1['title'] = o.text(),
        dic1['hot'] = i.text(),
        dic1['href'] = e.attr('href')
        save_mongo(dic1)
#        print(dic1)

    
if __name__ == '__main__':
    get_index()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值