首先分析街拍图集的网页请求头部:

在 preview 选项卡我们可以找到 json 文件,分析 data 选项,找到我们要找到的图集地址 article_url:

选中其中一张图片,分析 json 请求,可以找到图片地址在 gallery 一栏:

找到图片地址,接下来我们就可以来写代码了:

1.导入必要的库:

import requests
import json
import re
import pymongo
import os
from hashlib import md5
from multiprocessing import Pool
from json.decoder import JSONDecodeError
from requests.exceptions import RequestException
from urllib.parse import urlencode
from bs4 import BeautifulSoup

2.获取索引页并分析:

def get_page_index(offset, keyword):
data = {
'offset': offset,
'format': 'json',
'keyword': keyword,
'autoload': 'true',
'count': 20,
'cur_tab': 3
}
url = 'https://www.toutiao.com/search_content/?' + urlencode(data)
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
except RequestException:
print(' 请求索引页出错')
return None 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

3.获取详情页并分析:

def get_page_detail(url):
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
except RequestException:
print(' 请求详情页出错')
return None def parse_page_detail(html, url):
soup = BeautifulSoup(html, 'lxml')
title = soup.select('title')[0].get_text()
images_pattern = re.compile('gallery: (.*?),\n', re.S)
result = re.search(images_pattern, html)
if result:
data = json.loads(result.group(1))
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_images(image)
return {
'title': title,
'url': url,
'images': images
}

4.使用 MongoDB 数据库存储数据:

首先定义一个 config.py 文件,配置默认参数:

写入 MongoDB:

def save_to_mongo(result):
if db[MONGO_TABLE].insert(result):
print(' 存储到 MongoDB 成功', result)
return True

5.存储图片到本地:

def download_images(url):
print(' 正在下载', url)
try:
response = requests.get(url)
if response.status_code == 200:
save_images(response.content)
return None
except RequestException:
print(' 请求图片出错')
return None def save_images(content):
file_path = '{0}/{1}.{2}'.format(os.getcwd(), md5(content).hexdigest(), 'jpg')
if not os.path.exists(file_path):
with open(file_path, 'wb') as f:
f.write(content)
f.close()

6.最后定义 main()函数,并开启多线程抓取20页图集:

def save_images(content):
file_path = '{0}/{1}.{2}'.format(os.getcwd(), md5(content).hexdigest(), 'jpg')
if not os.path.exists(file_path):
with open(file_path, 'wb') as f:
f.write(content)
f.close() def main(offset):
text = get_page_index(offset, KEYWORD)
for url in parse_page_index(text):
html = get_page_detail(url)
if html:
result = parse_page_detail(html, url)
if result:
save_to_mongo(result) if __name__ == '__main__':
groups = [x * 20 for x in range(GROUP_START, GROUP_END + 1)]
pool = Pool()
pool.map(main, groups)

代码GitHub地址:https://github.com/weixuqin/PythonProjects/tree/master/jiepai

分析 ajax 请求并抓取今日头条街拍美图的更多相关文章

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

    项目说明 本项目以今日头条为例,通过分析Ajax请求来抓取网页数据. 有些网页请求得到的HTML代码里面并没有我们在浏览器中看到的内容.这是因为这些信息是通过Ajax加载并且通过JavaScript渲 ...

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

    import requests from urllib.parse import urlencode # 引入异常类 from requests.exceptions import RequestEx ...

  3. python爬虫知识点总结(十)分析Ajax请求并抓取今日头条街拍美图

    一.流程框架

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

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

  5. Python爬虫系列-分析Ajax请求并抓取今日头条街拍图片

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

  6. 【Python爬虫案例学习】分析Ajax请求并抓取今日头条街拍图片

    1.抓取索引页内容 利用requests请求目标站点,得到索引网页HTML代码,返回结果. from urllib.parse import urlencode from requests.excep ...

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

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

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

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

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

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

随机推荐

  1. Mysql 一次性备份导出/导入恢复所有数据库

    有木有遇到过这种情况?电脑或者服务器需要重装系统?可是你电脑上存着n多个网站的数据库,怎么办?把数据库文件夹拷贝出来,重装系统之后再拷回去?如果你使用了InnoDB引擎,恐怕那样做会出麻烦的,一个一个 ...

  2. Chrome浏览器及调试教程

    ==>(微信公众号:IT知更鸟)欢迎关注<^>@<^> Chrome浏览器及调试教程 在web开发过程中,我们在写JavaScript脚本时难免会遇到各种bug,这时,我 ...

  3. 第2次作业:Wechat创作史

    Wechat创作史   比尔盖茨曾经说过一句话:21世纪要么电子商务,要么无商可务. 2.1 介绍产品相关信息 -the information about Wechat 你选择的产品是? 选择微信作 ...

  4. java第5章学习总结

    学号20145336 <Java程序设计>第5周学习总结 教材学习内容总结 try catch JVM会先尝试执行try区块中的内容,若发生错误且与catch后面的类型相符,则执行catc ...

  5. python学习笔记-问题

    1.字典按照值进行排序输出 2.返回函数-闭包的使用

  6. python的项目结构

    项目结构 知识点 创建项目,编写 __init__ 文件 使用 setuptools 模块,编写 setup.py 和 MANIFEST.in 文件 创建源文件的发布版本 项目注册&上传到 P ...

  7. HTTP协议中PUT和POST使用区别

          有的观点认为,应该用POST来创建一个资源,用PUT来更新一个资源:有的观点认为,应该用PUT来创建一个资源,用POST来更新一个资源:还有的观点认为可以用PUT和POST中任何一个来做创 ...

  8. Webview之H5页面调用android的图库及文件管理

    h5页面打开图片管理器 一般页面在pc打开文件管理器是用 type="file"的代码,可是这在android的webview是无效的,必须为webview设定WebChromeC ...

  9. 再议Python协程——从yield到asyncio

    协程,英文名Coroutine.前面介绍Python的多线程,以及用多线程实现并发(参见这篇文章[浅析Python多线程]),今天介绍的协程也是常用的并发手段.本篇主要内容包含:协程的基本概念.协程库 ...

  10. nyoj n-1位数

    n-1位数 时间限制:3000 ms  |  内存限制:65535 KB 难度:1   描述 已知w是一个大于10但不大于1000000的无符号整数,若w是n(n≥2)位的整数,则求出w的后n-1位的 ...