精易论坛

标题: Python实例记录----Ajax爬取与MongoDB文档储存 [打印本页]

作者: 菠萝儿    时间: 2022-3-2 23:46
标题: Python实例记录----Ajax爬取与MongoDB文档储存
本帖最后由 菠萝儿 于 2022-3-2 23:50 编辑

[Python] 纯文本查看 复制代码
import requests
import logging
import pymongo

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')  # 定义logging基本配置

INDRX_URL = 'https://spa1.scrape.center/api/movie/?limit={limit}&offset={offset}'


# 定义每页链接url,把limit和offset预留出来变成占位符,可以动态传入参数构造一个完整的列表页url


def scrape_api(url):  # 详情页爬取
    logging.info('scraping %s...', url)
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.json()  # 页面响应成功后,将响应内容以JSON格式返回
        logging.error('get invalid status code %s while scraping %s', response.status_code, url)  # 不成功打印错误日志
    except requests.RequestException:  # 处理错误
        logging.error('error occurred ehile scraping %s', url, exc_info=True)
        #  exc_info参数的值为True时,则会将异常信息添加到日志消息中;如果没有则会将None添加到日志信息中。


LIMIT = 10


def scrape_index(page):  # 定义方法,接收参数page(列表页的页码)
    url = INDRX_URL.format(limit=LIMIT, offset=LIMIT * (page - 1))  # 构造url,完善链接
    return scrape_api(url)  # 将链接传入scrape_api()方法中,返回列表页内容


DETAIL_URL = 'https://spa1.scrape.center/api/movie/{id}'  # 详情链接


def scrape_detail(id):
    url = DETAIL_URL.format(id=id)  # 构造url,完善链接
    return scrape_api(url)  # 将链接传入scrape_api()方法中,返回详情内容


TOTAL_PAGE = 10  # 确定总页数


def main():
    for page in range(TOTAL_PAGE + 1):  # 遍历页码
        index_data = scrape_index(page)  # 返回列表页数据
        for item in index_data.get('results'):  # 遍历列表页数据
            id = item.get('id')  # 获取每部电影id
            detail_data = scrape_detail(id)  # 返回电影详情数据
            logging.info('setail data %s', detail_data)  # 打印日志
            save_data(detail_data)
            logging.info('data saved successfully')


MONGO_CONNECTION_STRING = 'mongodb://localhost:27017'  # 数据库连接信息,IP:端口
MONGO_DB_NAME = 'movies'  # 数据库名称
MONGO_CONNECTION_NAME = 'movies'  # 集合名称

client = pymongo.MongoClient(MONGO_CONNECTION_STRING)  # 连接数据库
db = client['movies']  # 指定数据库
collection = db['movies']  # 指定集合


def save_data(data):
    collection.update_one({
        'name': data.get('name')  # 在data数据中获取name,作为查询条件
    }, {
        '$set': data
    }, upsert=True)
# updata_one()更新方法,第一个参数是查询条件,即为根据name查询,第二个参数是data对象本身,就是所有数据,用$set操作符表示更新
# upsert=True 可以实现存在即更新(数据库中含有name就替换为新的),不存在即插入  可以防止数据库中出现同名电影数据  !!!去重效果!!!

if __name__ == '__main__':
    main()


作者: tramsky    时间: 2022-8-30 16:52
想知道易语言怎么存




欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4