1.抓取索引页内容

利用requests请求目标站点,得到索引网页HTML代码,返回结果。

from urllib.parse import urlencode
from requests.exceptions import RequestException
import requests
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
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.下载图片与保存数据库

将图片下载到本地,并把页面信息及图片URL保存到MongDB。

# 存到数据库
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)

完整代码:

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
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
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请求并抓取今日头条街拍图片的更多相关文章

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

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

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

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

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

    首先分析街拍图集的网页请求头部: 在 preview 选项卡我们可以找到 json 文件,分析 data 选项,找到我们要找到的图集地址 article_url: 选中其中一张图片,分析 json 请 ...

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

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

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

    一.流程框架

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

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

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

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

  8. 爬虫七之分析Ajax请求并爬取今日头条

    爬取今日头条图片 这里只讨论出现的一些问题,代码在最下面github链接里. 首先,今日头条取消了"图集"这一选项,因此对于爬虫来说效率降低了很多: 在所有代码都完成后,也许是爬取 ...

  9. 分析 ajax 请求并抓取 “今日头条的街拍图”

    今日头条抓取页面: 分析街拍页面的 ajax 请求: 通过在 XHR 中查看内容,获取 url 链接,params 参数信息,将两者进行拼接后取得完整 url 地址.data 中的 article_u ...

随机推荐

  1. [RN] React Native 封装选择弹出框(ios&android)

    之前看到react-native-image-picker中自带了一个选择器,可以选择拍照还是图库,但我们的项目中有多处用到这个选择弹出框,所以就自己写了一下,最最重要的是ios和Android通用. ...

  2. .net web.config中配置字符串中特殊字符的处理

    https://www.cnblogs.com/zzmzaizai/archive/2008/01/30/1059191.html 如果本身字符串中有特殊字符,如分号,此时就需要用单引号整体包裹起来, ...

  3. 避免MySQL出现重复数据处理方法

    对于常规的MySQL数据表中可能存在重复的数据,有些情况是允许重复数据的存在,有些情况是不允许的,这个时候我们就需要查找并删除这些重复数据,以下是具体的处理方法! 方法一:防止表中出现重复数据 当表中 ...

  4. 前端知识点回顾之重点篇——CSS中flex布局

    flex布局 来源: http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html?utm_source=tuicool 采用 Flex 布局的元素 ...

  5. 从 SVN 迁移至 Git 并保留所有 commit 记录

    yum install -y git-svn 用户映射文件user.txt,等号左边为svn账号,右边为Git用户名和邮箱.注意:svn中有多少用户就要映射多少 test1=test1<1472 ...

  6. javascript常用方法 - String

    // 1.长字符串 // 1.1 let longString1 = "This is a very long string which needs " + "to wr ...

  7. https://www.jianshu.com/p/1038c6170775

    import os # 方法一: os.walk实现 def items_dir(rootname): l = [] for main_dir, dirs, file_name_list in os. ...

  8. c# Mono.Cecil IL方式 读MethodBody

    using Kufen.Common.Definitions; using Mono.Cecil; using System; using System.Collections.Generic; us ...

  9. 如何上传本地jar至远程仓库供其他项目使用

    我们首先需要创建自己内部nexus私服仓库.这里假设你已经做好了. 其次我们要明白nexus上如下几个component的用处. maven-central:maven中央库,默认从https://r ...

  10. Linux(CentOS)安装JDK1.8

    1.JDK的RPM包安装方式: https://www.cnblogs.com/hunttown/p/5450463.html 2.JDK的tar包安装方式: 首先,从SUN公司网站下载最新的JDK ...