前提:.需要安装MongDB

注:因今日投票网页发生变更,如下代码不保证能正常使用

#!/usr/bin/env python
#-*- coding: utf-8 -*- import json
import os
from urllib.parse import urlencode
import pymongo
import requests
from bs4 import BeautifulSoup
from requests.exceptions import ConnectionError
import re
from multiprocessing import Pool
from hashlib import md5
from json.decoder import JSONDecodeError MONGO_URL = 'localhost'
MONGO_DB = 'toutiao'
MONGO_TABLE = 'toutiao' GROUP_START = 1
GROUP_END = 20
KEYWORD='街拍' client = pymongo.MongoClient(MONGO_URL, connect=False)
db = client[MONGO_DB] def get_page_index(offset, keyword):
data = {
'autoload': 'true',
'count': 20,
'cur_tab': 3,
'format': 'json',
'keyword': keyword,
'offset': offset,
}
params = urlencode(data)
base = 'http://www.toutiao.com/search_content/'
url = base + '?' + params
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
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 ConnectionError:
return None def save_image(content):
file_path = '{0}/{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 parse_page_index(text):
try:
data = json.loads(text)
if data and 'data' in data.keys():
for item in data.get('data'):
yield item.get('article_url')
except JSONDecodeError:
pass def get_page_detail(url):
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
except ConnectionError:
print('Error occurred')
return None def parse_page_detail(html, url):
soup = BeautifulSoup(html, 'lxml')
result = soup.select('title')
title = result[0].get_text() if result else ''
images_pattern = re.compile('gallery: JSON.parse\("(.*)"\)', re.S)
result = re.search(images_pattern, html)
if result:
data = json.loads(result.group(1).replace('\\', ''))
if data and 'sub_images' in data.keys():
sub_images = data.get('sub_images')
images = [item.get('url') for item in sub_images]
for image in images: download_image(image)
return {
'title': title,
'url': url,
'images': images
} def save_to_mongo(result):
if db[MONGO_TABLE].insert(result):
print('Successfully Saved to Mongo', result)
return True
return False def main(offset):
text = get_page_index(offset, KEYWORD)
urls = parse_page_index(text)
for url in urls:
html = get_page_detail(url)
print(html)
result = parse_page_detail(html, url)
print(result)
if result: save_to_mongo(result) 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()

分析Ajax来爬取今日头条街拍美图并保存到MongDB的更多相关文章

  1. 爬虫(八):分析Ajax请求抓取今日头条街拍美图

    (1):分析网页 分析ajax的请求网址,和需要的参数.通过不断向下拉动滚动条,发现请求的参数中offset一直在变化,所以每次请求通过offset来控制新的ajax请求. (2)上代码 a.通过aj ...

  2. python3爬虫-分析Ajax,抓取今日头条街拍美图

    # coding=utf-8 from urllib.parse import urlencode import requests from requests.exceptions import Re ...

  3. 【Python3网络爬虫开发实战】 分析Ajax爬取今日头条街拍美图

    前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:haoxuan10 本节中,我们以今日头条为例来尝试通过分析Ajax请求 ...

  4. 【Python3网络爬虫开发实战】6.4-分析Ajax爬取今日头条街拍美图【华为云技术分享】

    [摘要] 本节中,我们以今日头条为例来尝试通过分析Ajax请求来抓取网页数据的方法.这次要抓取的目标是今日头条的街拍美图,抓取完成之后,将每组图片分文件夹下载到本地并保存下来. 1. 准备工作 在本节 ...

  5. 转:【Python3网络爬虫开发实战】6.4-分析Ajax爬取今日头条街拍美图

    [摘要] 本节中,我们以今日头条为例来尝试通过分析Ajax请求来抓取网页数据的方法.这次要抓取的目标是今日头条的街拍美图,抓取完成之后,将每组图片分文件夹下载到本地并保存下来. 1. 准备工作 在本节 ...

  6. 分析Ajax爬取今日头条街拍美图-崔庆才思路

    站点分析 源码及遇到的问题 代码结构 方法定义 需要的常量 关于在代码中遇到的问题 01. 数据库连接 02.今日头条的反爬虫机制 03. json解码遇到的问题 04. 关于response.tex ...

  7. python爬虫之分析Ajax请求抓取抓取今日头条街拍美图(七)

    python爬虫之分析Ajax请求抓取抓取今日头条街拍美图 一.分析网站 1.进入浏览器,搜索今日头条,在搜索栏搜索街拍,然后选择图集这一栏. 2.按F12打开开发者工具,刷新网页,这时网页回弹到综合 ...

  8. 15-分析Ajax请求并抓取今日头条街拍美图

    流程框架: 抓取索引页内容:利用requests请求目标站点,得到索引网页HTML代码,返回结果. 抓取详情页内容:解析返回结果,得到详情页的链接,并进一步抓取详情页的信息. 下载图片与保存数据库:将 ...

  9. Python Spider 抓取今日头条街拍美图

    """ 抓取今日头条街拍美图 """ import os import time import requests from hashlib ...

随机推荐

  1. 【slighttpd】基于lighttpd架构的Server项目实战(6)—预备知识之Http

    接下来,我们開始http部分的开发. 在此之前.有必要先学习一下HTTP协议- http1.1 的rfc文档:http://www.ietf.org/rfc/rfc2616.txt 简单介绍 超文本传 ...

  2. 【SpringMVC架构】SpringMVC入门实例,解析工作原理(二)

    上篇博文,我们简单的介绍了什么是SpringMVC.这篇博文.我们搭建一个简单SpringMVC的环境,使用非注解形式实现一个HelloWorld实例,从简单入手,逐步深入. 环境准备 我们须要有主要 ...

  3. 关于使用chrome插件改动全部的站点的响应responseHeaders头的注意

    1 眼下我掌握的调试技巧非常不方便,如今使用的是浏览器动作,每次都须要点击那个popup页面弹出,然后右键->查看元素,才干显示它的调试面板.一点击某些位置它又没有了; 2 改动响应报头的值时, ...

  4. POJ2230题解

    题目来源 id=2230">http://poj.org/problem?id=2230 题目大意 求无向图从起点1開始从不同方向经过全部边的一条路径.输出随意一条. 题解 把无向图的 ...

  5. vbs脚本

    巧用Vbs SendKeys 可以做的事 发布: 2014-04-06 10:00:20 | 作者: | 来源: 按键精灵资源站 巧妙使用VBS中的SendKeys命令(这个命令的作用就是模拟键盘操作 ...

  6. Linux下安装JRE和Eclipse IDE for C/C++ Developers

    Linux32位,下载eclipse-cpp-luna-R-linux-gtk.tar.gz和jre-8u11-linux-i586.rpm  放到家文件夹中. http://www.eclipse. ...

  7. [NOIP 2007] 树网的核

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=1999 [算法] 树的直径 + 单调队列 [代码] #include<bits/ ...

  8. 【SCOI 2005】 骑士精神

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=1085 [算法] IDA* [代码] #include<bits/stdc++. ...

  9. python 下串口数据的读取,解析,和保存-

    #!/usr/bin/python # -*-coding: utf-8 -*- import serial import threading import binascii from datetim ...

  10. OCC 矩阵变换

    在OpenCADCADE中, 通过gp_Trsf类来进行矩阵变换操作, 采用矩阵在左的方式: 新点 = 变换矩阵 * 点 基本原理如下: //! Defines a non-persistent tr ...