Python的Requests来爬取今日头条的图片和文章

简介: Python的Requests来爬取今日头条的图片和文章

Python的Requests来爬取今日头条的图片和文章并且存入mongo

config.py

MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_DB = 'toutiao'
MONGO_TABLE = 'toutiao'
GROUP_START = 1
GROUP_END = 20
KEYWORD = '原油'

toutiao.py

import json
import os
from urllib.parse import urlencode
import pymongo
import requests
from multiprocessing import Pool
from requests.exceptions import ConnectionError
from hashlib import md5
from config import *
client = pymongo.MongoClient(MONGO_HOST, MONGO_PORT)
db = client[MONGO_DB]
def get_page_index(offset, keyword):
    data = {
        'autoload': 'true',
        'count': 20,
        'cur_tab': 1,
        'app_name': 'web_search',
        'format': 'search_tab',
        'keyword': keyword,
        'offset': offset,
    }
    params = urlencode(data)
    base = 'https://www.toutiao.com/api/search/content'
    url = base + '?' + params
    try:
        response = requests.get(url)
        if response.status_code == 200:
            data = json.loads(response.text)
            if data  and 'data' in data.keys():
                if data.get('data') is not None:
                    for item in data.get('data'):
                        if item is not None:
                           yield [item.get('article_url'), item.get('abstract'), item.get('large_image_url')]
    except ConnectionError:
        print('Error occurred')
        return None
def download_image(url):
    print('Downloading', url)
    try:
        response = requests.get(url)
        if response.status_code == 200:
            save_image(response.content)
        return None
    except Exception:
        return None
def save_image(content):
    file_path = '{0}/picture/{1}.{2}'.format(os.getcwd(), md5(content).hexdigest(), 'jpg')
    print(file_path)
    if not os.path.exists(file_path):
        with open(file_path, 'wb') as f:
            f.write(content)
            f.close()
def save_to_mongo(result):
    if db[MONGO_TABLE].insert_one(result):
        print('Successfully Saved to Mongo', result)
        return True
    return False
def main(offset):
    items = get_page_index(offset, KEYWORD)
    for item in items:
            if (item[2] is not None) and len(item[2])!=0:
                download_image(item[2])
            if (item[0] is not None and len(item[0]) != 0)\
                    or  (item[1] is not None and len(item[1]) != 0)\
                    or  (item[2] is not None and len(item[2]) != 0):
                json = {
                    'article_url': item[0],
                    'abstract': item[1],
                    'large_image_url': item[2]
                }
                save_to_mongo(json)
if __name__ == '__main__':
    pool = Pool()
    groups = ([x * 20 for x in range(GROUP_START, GROUP_END + 1)])
    pool.map(main, groups)
    pool.close()
    pool.join()

知识拓展:

一、用Flask+Redis维护Cookies池

为什什么要⽤用Cookies池

⽹网站需要登录才可爬取,例例如新浪微博

爬取过程中如果频率过⾼高会导致封号

需要维护多个账号的Cookies池实现⼤大规模爬取

Cookies池的要求

⾃自动登录更更新

定时验证筛选

提供外部接⼝口

代码:https://github.com/Python3WebSpider/CookiesPool

二、用Flask+Redis维护代理池

为什么要⽤用代理理池?

许多⽹网站有专⻔门的反爬⾍虫措施,可能遇到封IP等问题。

互联⽹网上公开了了⼤大量量免费代理理,利利⽤用好资源。

通过定时的检测维护同样可以得到多个可⽤用代理理。

代理理池的要求

多站抓取,异步检测

定时筛选,持续更更新

提供接⼝口,易易于提取

 

代码:https://github.com/Python3WebSpider/ProxyPool

三、VirtualEnv

  Virtualenv他最大的好处是,可以让每一个python项目单独使用一个环境,而不会影响python系统环境,也不会影响其他项目的环境。

安装,virtualenv本质上是个python包, 使用pip安装:

pip install virtualenv

在工作目录下创建虚拟环境(默认在当前目录):注意需要自定义虚拟环境的名字!

~$virtualenv TestEnv
New python executable in ~/TestEnv/bin/python
Installing setuptools, pip, wheel...done.

默认情况下, 虚拟环境中不包括系统的site-packages, 若要使用请添加参数:

语法:virtualenv --system-site-packages TestEnv

使用virtualenv默认python版本创建虚拟环境

语法:virtualenv --no-site-packages ubuntu_env

四、url去重策略


相关文章
|
10天前
|
Python
Python实用记录(六):如何打开txt文档并删除指定绝对路径下图片
这篇文章介绍了如何使用Python打开txt文档,删除文档中指定路径的图片,并提供了一段示例代码来展示这一过程。
21 1
|
11天前
|
计算机视觉 Python
Python实用记录(一):如何将不同类型视频按关键帧提取并保存图片,实现图片裁剪功能
这篇文章介绍了如何使用Python和OpenCV库从不同格式的视频文件中按关键帧提取图片,并展示了图片裁剪的方法。
38 0
|
5天前
|
网络协议 数据库连接 Python
python知识点100篇系列(17)-替换requests的python库httpx
【10月更文挑战第4天】Requests 是基于 Python 开发的 HTTP 库,使用简单,功能强大。然而,随着 Python 3.6 的发布,出现了 Requests 的替代品 —— httpx。httpx 继承了 Requests 的所有特性,并增加了对异步请求的支持,支持 HTTP/1.1 和 HTTP/2,能够发送同步和异步请求,适用于 WSGI 和 ASGI 应用。安装使用 httpx 需要 Python 3.6 及以上版本,异步请求则需要 Python 3.8 及以上。httpx 提供了 Client 和 AsyncClient,分别用于优化同步和异步请求的性能。
python知识点100篇系列(17)-替换requests的python库httpx
|
10天前
|
Python
Socket学习笔记(二):python通过socket实现客户端到服务器端的图片传输
使用Python的socket库实现客户端到服务器端的图片传输,包括客户端和服务器端的代码实现,以及传输结果的展示。
67 3
Socket学习笔记(二):python通过socket实现客户端到服务器端的图片传输
|
10天前
|
Python
Python实用记录(四):os模块-去后缀或者改后缀/指定目录下图片或者子目录图片写入txt/csv
本文介绍了如何使用Python的os模块来操作文件,包括更改文件后缀、分割文件路径和后缀、将指定目录下的所有图片写入txt文档,以及将指定目录下所有子目录中的图片写入csv文档,并为每个子目录分配一个标签。
10 1
|
12天前
|
存储 网络协议 API
详解Python中的Requests会话管理
详解Python中的Requests会话管理
|
14天前
|
编解码 UED Python
Python批量修改指定目录下图片的大小名文章
Python批量修改指定目录下图片的大小名文章
11 1
|
16天前
|
iOS开发 MacOS Python
Python编程小案例—利用flask查询本机IP归属并输出网页图片
Python编程小案例—利用flask查询本机IP归属并输出网页图片
16 1
|
14天前
|
Python
Python实现图片的拼接
Python实现图片的拼接
12 0
|
14天前
|
存储 自然语言处理 数据库
Python字典操作实现文章敏感词检索
Python字典操作实现文章敏感词检索
11 0