1.访问搜索图集结果,获得json如下(右图为data的一条的详细内容).页面以Ajax呈现,每次请求20个图集,其中

title     --- 图集名字

artical_url  --- 图集的地址

count    --- 图集图片数量

  

2. 访问其中的图集

   访问artical_url,获得图集图片详细信息,其中图片url为下载地址

展现出爬虫关键部分,整体项目地址在https://github.com/GeoffreyHub/toutiao_spider

 #!/usr/bin/env python
# encoding: utf-8 """
@version: python37
@author: Geoffrey
@file: spider.py
@time: 18-10-24 上午11:15
"""
import json
import re
from multiprocessing import Pool
import urllib3
urllib3.disable_warnings()
from requests import RequestException from common.request_help import make_session
from db.mysql_handle import MysqlHandler
from img_spider.settings import * class SpiderTouTiao: def __init__(self, keyword):
self.session = make_session(debug=True)
self.url_index = 'https://www.toutiao.com/search_content/'
self.keyword = keyword
self.mysql_handler = MysqlHandler(MYSQL_CONFIG) def search_index(self, offset):
url = self.url_index
data = {
'offset': f'{offset}',
'format': 'json',
'keyword': self.keyword,
'autoload': 'true',
'count': '',
'cur_tab': '',
'from': 'gallery'
} try:
response = self.session.get(url, params=data)
if response.status_code is 200:
json_data = response.json()
with open(f'../json_data/搜索结果-{offset}.json', 'w', encoding='utf-8') as f:
json.dump(json_data, f, indent=4, ensure_ascii=False)
return self.get_gallery_url(json_data)
except :
pass
print('请求失败') @staticmethod
def get_gallery_url(json_data):
dict_data = json.dumps(json_data)
for info in json_data["data"]:
title = info["title"]
gallery_pic_count = info["gallery_pic_count"]
article_url = info["article_url"]
yield title, gallery_pic_count, article_url def gallery_list(self, search_data):
gallery_urls = {}
for title, gallery_pic_count, article_url in search_data:
print(title, gallery_pic_count, article_url)
response = self.session.get(article_url)
html = response.text
images_pattern = re.compile('gallery: JSON.parse\("(.*?)"\),', re.S)
result = re.search(images_pattern, html) if result:
# result = result.replace('\\', '')
# result = re.sub(r"\\", '', result)
result = eval("'{}'".format(result.group(1)))
result = json.loads(result)
# picu_urls = zip(result["sub_abstracts"], result["sub_titles"], [url["url"] for url in result["sub_images"]])
picu_urls = zip(result["sub_abstracts"], [url["url"] for url in result["sub_images"]])
# print(list(picu_urls))
gallery_urls[title] = picu_urls
else:
print('解析不到图片url') with open(f'../json_data/{title}-搜索结果.json', 'w', encoding='utf-8') as f:
json.dump(result, f, indent=4, ensure_ascii=False) break # print(gallery_urls)
return gallery_urls def get_imgs(self, gallery_urls):
params = []
for title, infos in (gallery_urls.items()):
for index, info in enumerate(infos):
abstract, img_url = info
print(index, abstract)
response = self.session.get(img_url)
img_content = response.content
params.append([title, abstract, img_content]) with open(f'/home/geoffrey/图片/今日头条/{title}-{index}.jpg', 'wb') as f:
f.write(img_content) SQL = 'insert into img_gallery(title, abstract, imgs) values(%s, %s, %s)'
self.mysql_handler.insertOne(SQL, [title, abstract, img_content])
self.mysql_handler.end() print(f'保存图集完成' + '-'*50 )
# SQL = 'insert into img_gallery(title, abstract, imgs) values(%s, %s, %s)'
# self.mysql_handler.insertMany(SQL, params)
# self.mysql_handler.end() def main(offset):
spider = SpiderTouTiao(KEY_WORD)
search_data = spider.search_index(offset)
gallery_urls = spider.gallery_list(search_data)
spider.get_imgs(gallery_urls)
spider.mysql_handler.dispose() if __name__ == '__main__':
groups = [x*20 for x in range(GROUP_START, GROPE_END)] pool = Pool(10)
pool.map(main, groups) # for i in groups:
# main(i)

项目结构如下:

.
├── common
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-37.pyc
│ │ └── request_help.cpython-37.pyc
│ ├── request_help.py
├── db
│ ├── __init__.py
│ ├── mysql_handle.py
│ └── __pycache__
│ ├── __init__.cpython-37.pyc
│ └── mysql_handle.cpython-37.pyc
├── img_spider
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-37.pyc
│ │ └── settings.cpython-37.pyc
│ ├── settings.py
│ └── spider.py
└── json_data
├── 沐浴三里屯的秋-搜索结果.json
├── 盘点三里屯那些高逼格的苍蝇馆子-搜索结果.json
├── 搜索结果-0.json
├── 搜索结果-20.json
├── 搜索结果-40.json

python爬取今日头条关键字图集的更多相关文章

  1. Python爬取今日头条段子

    刚入门Python爬虫,试了下爬取今日头条官网中的段子,网址为https://www.toutiao.com/ch/essay_joke/源码比较简陋,如下: import requests impo ...

  2. python爬取今日头条图片

    import requests from urllib.parse import urlencode from requests import codes import os # qianxiao99 ...

  3. PYTHON 爬虫笔记九:利用Ajax+正则表达式+BeautifulSoup爬取今日头条街拍图集(实战项目二)

    利用Ajax+正则表达式+BeautifulSoup爬取今日头条街拍图集 目标站点分析 今日头条这类的网站制作,从数据形式,CSS样式都是通过数据接口的样式来决定的,所以它的抓取方法和其他网页的抓取方 ...

  4. python 简单爬取今日头条热点新闻(一)

    今日头条如今在自媒体领域算是比较强大的存在,今天就带大家利用python爬去今日头条的热点新闻,理论上是可以做到无限爬取的: 在浏览器中打开今日头条的链接,选中左侧的热点,在浏览器开发者模式netwo ...

  5. 分析ajax请求抓取今日头条关键字美图

    # 目标:抓取今日头条关键字美图 # 思路: # 一.分析目标站点 # 二.构造ajax请求,用requests请求到索引页的内容,正则+BeautifulSoup得到索引url # 三.对索引url ...

  6. Python3从零开始爬取今日头条的新闻【一、开发环境搭建】

    Python3从零开始爬取今日头条的新闻[一.开发环境搭建] Python3从零开始爬取今日头条的新闻[二.首页热点新闻抓取] Python3从零开始爬取今日头条的新闻[三.滚动到底自动加载] Pyt ...

  7. Python3从零开始爬取今日头条的新闻【四、模拟点击切换tab标签获取内容】

    Python3从零开始爬取今日头条的新闻[一.开发环境搭建] Python3从零开始爬取今日头条的新闻[二.首页热点新闻抓取] Python3从零开始爬取今日头条的新闻[三.滚动到底自动加载] Pyt ...

  8. Python3从零开始爬取今日头条的新闻【三、滚动到底自动加载】

    Python3从零开始爬取今日头条的新闻[一.开发环境搭建] Python3从零开始爬取今日头条的新闻[二.首页热点新闻抓取] Python3从零开始爬取今日头条的新闻[三.滚动到底自动加载] Pyt ...

  9. Python3从零开始爬取今日头条的新闻【二、首页热点新闻抓取】

    Python3从零开始爬取今日头条的新闻[一.开发环境搭建] Python3从零开始爬取今日头条的新闻[二.首页热点新闻抓取] Python3从零开始爬取今日头条的新闻[三.滚动到底自动加载] Pyt ...

随机推荐

  1. Windows Service 2012 R2 下如何建立ftp服务器

    1.首先在本地机器上创建一个用户!这些用户是用来登录到FTP的!我的电脑右键->管理->本地用户和组->用户->“右键”新建用户->输入用户名和密码再点创建就行了! 2. ...

  2. 自定义Form组件

    一.wtforms源码流程 1.实例化流程分析 # 源码流程 1. 执行type的 __call__ 方法,读取字段到静态字段 cls._unbound_fields 中: meta类读取到cls._ ...

  3. Let the Balloon Rise <map>的应用

    Contest time again! How excited it is to see balloons floating around. But to tell you a secret, the ...

  4. SpringBoot图片上传(二)

    需求简介:做新增的时候,需要上传图片.(⊙o⊙)…这需求描述也太简单了吧,限制文件大小60*60 512kb ,第一次做,记录一下嗷,废话就不啰嗦了 上代码 代码: //html代码<div c ...

  5. 剑指offer 二叉树的层序遍历

    剑指offer 牛客网 二叉树的层序遍历 # -*- coding: utf-8 -*- """ Created on Tue Apr 9 09:33:16 2019 @ ...

  6. java----static关键字(包括final)

    static修饰字段: 使用static关键字修饰一个字段:声明的static变量实际上就是一个全局变量 使用static关键字修饰一个方法:可以直接使用类调用方法,和对象没有关系了 使用static ...

  7. cf round546 cde

    第一题会卡一下同时用set和cin.. 其他的注意下矩阵对角线下标的应用即可 #include<bits/stdc++.h> using namespace std; #define ma ...

  8. Nginx详解十六:Nginx场景实践篇之缓存服务

    缓存类型: 服务端缓存 代理缓存 客户端缓存 Nginx代理缓存 配置语法 使用之前需要先定义一个proxy_cache_path配置语法:proxy_cache_path path [levels= ...

  9. Docker快速部署gitlab

    环境: Centos7.5 安装Docker 1.移除旧版本: $ sudo yum remove docker \ docker-client \ docker-client-latest \ do ...

  10. 使用asp.net MVC的 HtmlHelper 时遇到的小问题,报错:Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

    异常信息:Templates can be used only with field access, property access, single-dimension array index, or ...