Python爬虫系列-分析Ajax请求并抓取今日头条街拍图片
1.抓取索引页内容
利用requests请求目标站点,得到索引网页HTML代码,返回结果。
2.抓取详情页内容
解析返回结果,得到详情页的链接,并进一步抓取详情页的信息。
3.下载图片与保存数据库
将图片下载到本地,并把页面信息及图片URL保存到MongDB。
4.开启循环及多线程
对多页内容遍历,开启多线程提高抓取速度。
1.抓取索引页
from urllib.parse import urlencode
from requests.exceptions import RequestException
import requests
def get_page_index(offset, keyword):
headers = { 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' }
data = {
'format': 'json',
'offset': offset,
'keyword': keyword,
'autoload': 'true',
'count': 20,
'cur_tab': 1,
'from': 'search_tab',
'pd': 'synthesis',
}
url = 'https://www.toutiao.com/search_content/?' + urlencode(data)
response = requests.get(url, headers=headers);
try:
if response.status_code == 200:
return response.text
return None
except RequestException:
print('请求索引页失败')
return None
def main():
html = get_page_index(0,'街拍')
print(html)
if __name__=='__main__':
main()
2.抓取详情页内容
获取页面网址:
def parse_page_index(html):
data = json.loads(html)
if data and 'data' in data.keys():
for item in data.get('data'):
yield item.get('article_url')
单个页面代码:
def get_page_detail(url):
headers = { 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' }
try:
response = requests.get(url, headers=headers)
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: JSON.parse\((.*?)\)', re.S)
result = re.search(images_pattern, html)
if result:
data = json.loads(result.group(1))
data = json.loads(data) #将字符串转为dict,因为报错了
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,
'images':images,
'url':url
}
3.下载图片与保存数据库
# 存到数据库
def save_to_mongo(result):
if db[MONGO_TABLE].insert(result):
print('存储到MongoDb成功', result)
return True
return False
# 下载图片
def download_image(url):
print('正在下载',url)
headers = { 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537. 36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' }
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
save_image(response.content)
return None
except RequestException:
print('请求图片失败', url)
return None
def save_image(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)
4.开启循环及多线程
groups = [x*20 for x in range(GROUP_START, GROUP_END+1)]
pool = Pool()
pool.map(main,groups)
完整代码:spider.py
from urllib.parse import urlencode
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
from hashlib import md5
from multiprocessing import Pool
from config import *
import pymongo
import requests
import json
import re
import os
client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]
def get_page_index(offset, keyword):
headers = { 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' }
data = { 'format': 'json','offset': offset,'keyword': keyword,'autoload': 'true','count': 20,'cur_tab': 1,'from': 'search_tab','pd': 'synthesis' }
url = 'https://www.toutiao.com/search_content/?' + urlencode(data)
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
except RequestException:
print('请求索引页失败')
return None
def parse_page_index(html):
data = json.loads(html)
if data and 'data' in data.keys():
for item in data.get('data'):
yield item.get('article_url')
def get_page_detail(url):
headers = { 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' }
try:
response = requests.get(url, headers=headers)
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: JSON.parse\((.*?)\)', re.S)
result = re.search(images_pattern, html)
if result:
data = json.loads(result.group(1))
data = json.loads(data) #将字符串转为dict,因为报错了
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,
'images':images,
'url':url
}
def save_to_mongo(result):
if db[MONGO_TABLE].insert(result):
print('存储到MongoDb成功', result)
return True
return False
def download_image(url):
print('正在下载',url)
headers = { 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537. 36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' }
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
save_image(response.content)
return None
except RequestException:
print('请求图片失败', url)
return None
def save_image(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)
def main(offset):
html = get_page_index(offset,KEYWORD)
for url in parse_page_index(html):
html = get_page_detail(url)
if html:
result = parse_page_detail(html,url)
if isinstance(result,dict):
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)
config.py
MONGO_URL = 'localhost'
MONGO_DB = 'toutiao'
MONGO_TABLE = 'jiepai'
GROUP_START = 1
GROUP_END = 20
KEYWORD = '街拍'
~
Python爬虫系列-分析Ajax请求并抓取今日头条街拍图片的更多相关文章
- 【Python爬虫案例学习】分析Ajax请求并抓取今日头条街拍图片
1.抓取索引页内容 利用requests请求目标站点,得到索引网页HTML代码,返回结果. from urllib.parse import urlencode from requests.excep ...
- 分析Ajax请求并抓取今日头条街拍美图
项目说明 本项目以今日头条为例,通过分析Ajax请求来抓取网页数据. 有些网页请求得到的HTML代码里面并没有我们在浏览器中看到的内容.这是因为这些信息是通过Ajax加载并且通过JavaScript渲 ...
- 分析 ajax 请求并抓取今日头条街拍美图
首先分析街拍图集的网页请求头部: 在 preview 选项卡我们可以找到 json 文件,分析 data 选项,找到我们要找到的图集地址 article_url: 选中其中一张图片,分析 json 请 ...
- 2.分析Ajax请求并抓取今日头条街拍美图
import requests from urllib.parse import urlencode # 引入异常类 from requests.exceptions import RequestEx ...
- python爬虫知识点总结(十)分析Ajax请求并抓取今日头条街拍美图
一.流程框架
- 15-分析Ajax请求并抓取今日头条街拍美图
流程框架: 抓取索引页内容:利用requests请求目标站点,得到索引网页HTML代码,返回结果. 抓取详情页内容:解析返回结果,得到详情页的链接,并进一步抓取详情页的信息. 下载图片与保存数据库:将 ...
- 分析 ajax 请求并抓取 “今日头条的街拍图”
今日头条抓取页面: 分析街拍页面的 ajax 请求: 通过在 XHR 中查看内容,获取 url 链接,params 参数信息,将两者进行拼接后取得完整 url 地址.data 中的 article_u ...
- python爬虫之分析Ajax请求抓取抓取今日头条街拍美图(七)
python爬虫之分析Ajax请求抓取抓取今日头条街拍美图 一.分析网站 1.进入浏览器,搜索今日头条,在搜索栏搜索街拍,然后选择图集这一栏. 2.按F12打开开发者工具,刷新网页,这时网页回弹到综合 ...
- PYTHON 爬虫笔记九:利用Ajax+正则表达式+BeautifulSoup爬取今日头条街拍图集(实战项目二)
利用Ajax+正则表达式+BeautifulSoup爬取今日头条街拍图集 目标站点分析 今日头条这类的网站制作,从数据形式,CSS样式都是通过数据接口的样式来决定的,所以它的抓取方法和其他网页的抓取方 ...
随机推荐
- Uva11134
#include<bits/stdc++.h> #define inf 0x3f3f3f3f ; using namespace std; int n; struct rook{ int ...
- python 6 循环
循环 要计算1+2+3,我们可以直接写表达式: >>> 1 + 2 + 3 6 要计算1+2+3+...+10,勉强也能写出来. 但是,要计算1+2+3+...+10000,直接写表 ...
- C++ 11 Lambda表达式!!!!!!!!!!!
C++11的一大亮点就是引入了Lambda表达式.利用Lambda表达式,可以方便的定义和创建匿名函数.对于C++这门语言来说来说,“Lambda表达式”或“匿名函数”这些概念听起来好像很深奥,但很多 ...
- DevExpress GridControl 控件二表连动
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- Spring-boot原理(附带实现一个spring-boot-starter实例和代码下载)
(我就是个封面) Spring-boot自出现后,到现在火的很,大家貌似都在用,连招聘里面也要求会这个.但是说实话,spring-boot无外乎想实现一种可插拔的编程方式,说是简化配置,其实并没有 ...
- windows无法启动redis服务,错误码1067
https://blog.csdn.net/kissdead0xzy/article/details/84332870
- 《java学习三》并发编程 -------线程池原理剖析
阻塞队列与非阻塞队 阻塞队列与普通队列的区别在于,当队列是空的时,从队列中获取元素的操作将会被阻塞,或者当队列是满时,往队列里添加元素的操作会被阻塞.试图从空的阻塞队列中获取元素的线程将会被阻塞,直到 ...
- nodejs 实践:express 最佳实践(八) egg.js 框架的优缺点
nodejs 实践:express 最佳实践(八) egg.js 框架的优缺点 优点 所有的 web开发的点都考虑到了 agent 很有特色 文件夹规划到位 扩展能力优秀 缺点 最大的问题在于: 使用 ...
- 【持续更新】Java 时间相关
直接上代码: import java.util.*; import java.text.SimpleDateFormat; public class HelloWorld { public stati ...
- zuul 自定义路由映射规则
zuul本射自动创建eureka中的服务的路由