【Python爬虫案例学习】分析Ajax请求并抓取今日头条街拍图片
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请求并抓取今日头条街拍图片的更多相关文章
- Python爬虫系列-分析Ajax请求并抓取今日头条街拍图片
1.抓取索引页内容 利用requests请求目标站点,得到索引网页HTML代码,返回结果. 2.抓取详情页内容 解析返回结果,得到详情页的链接,并进一步抓取详情页的信息. 3.下载图片与保存数据库 将 ...
- 分析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代码,返回结果. 抓取详情页内容:解析返回结果,得到详情页的链接,并进一步抓取详情页的信息. 下载图片与保存数据库:将 ...
- PYTHON 爬虫笔记九:利用Ajax+正则表达式+BeautifulSoup爬取今日头条街拍图集(实战项目二)
利用Ajax+正则表达式+BeautifulSoup爬取今日头条街拍图集 目标站点分析 今日头条这类的网站制作,从数据形式,CSS样式都是通过数据接口的样式来决定的,所以它的抓取方法和其他网页的抓取方 ...
- 爬虫七之分析Ajax请求并爬取今日头条
爬取今日头条图片 这里只讨论出现的一些问题,代码在最下面github链接里. 首先,今日头条取消了"图集"这一选项,因此对于爬虫来说效率降低了很多: 在所有代码都完成后,也许是爬取 ...
- 分析 ajax 请求并抓取 “今日头条的街拍图”
今日头条抓取页面: 分析街拍页面的 ajax 请求: 通过在 XHR 中查看内容,获取 url 链接,params 参数信息,将两者进行拼接后取得完整 url 地址.data 中的 article_u ...
随机推荐
- H5实现横向滚动的方法总结
小程序中有横向滚动的swiper,H5中目前得手动实现. 实现方法如下: 外层需要设置: overflow: scroll;white-space: nowrap; 内层需要设置: display: ...
- space-cloud 支持多数据库多rest&& graphql web server
space-cloud 是一个开源的类似hasura 的graphql 引擎,但是space-cloud 同时支持rest api,而且支持多数据库 基于golang 编写,功能看着很强大 参考图 功 ...
- linux mustache bash 实现mo 做为docker容器运行动态配置工具数组的处理
前面有说过关于使用mo 工具的简单配置使用,但是实际中我们可能存在比较复杂的数据处理,比如数组,mo 可以进行数组的处理,但是在测试的过程中,一直失败,查看了官方的demo以及帮助命令发现可以通过参数 ...
- 进阶blog整理
https://blog.csdn.net/zhangerqing https://bbs.csdn.net/topics/310072893 SCJP
- uniapp 组件传参
父组件 <v-sub @returnDate=returnDate :backGround=backGround></v-sub> import vSub from " ...
- 站在BERT肩膀上的NLP新秀们(PART I)
站在BERT肩膀上的NLP新秀们(PART I)
- MLflow系列3:MLflow项目
英文链接:https://mlflow.org/docs/latest/projects.html 本文链接:https://www.cnblogs.com/CheeseZH/p/11945432.h ...
- Android TextView部分文字实现点击事件
This is the class for text whose content and markup can both be changed. (这是一个内容和标记都可以更改的文本类) 快速实现 直 ...
- 浅入深出ETCD之【集群部署与golang客户端使用】
前言 之前说了etcd的简介,命令行使用,一些基本原理.这次来说说现实一点的集群部署和golang版本的客户端使用.因为在实际使用过程中,etcd的节点肯定是需要2N+1个进行部署的,所以有必要说明一 ...
- Eclipse检出原MyEclipse项目后 javax.servlet.http相关类都报错【我,体现着一类jar包问题的处理方法】
用Eclipse检出原来为myEclipse搭建的一个项目,检出后,所有关于httpservlet的类都报异常,说有没实现的方法? 但这个项目之前人家用MyEclipse运行都是没有问题的, 按住CT ...