python AjaxSpider 代码演示
import re # 引入正则表达式
import json # 引入 json
import pymongo # 引入mongo数据库
import requests # 引入HTTP请求协议
from hashlib import md5 # 引入MD5
from bs4 import BeautifulSoup #引入BeautifulSoup 信息查询框架
from multiprocessing import Pool # 引入 多线程池
from urllib.parse import urlencode #引入网页解析
from json.decoder import JSONDecodeError #引入json错误异常
from requests.exceptions import RequestException #引入 HTTP异常 from config import * #导入数据库配置信息 client = pymongo.MongoClient(MONGO_URL,connect=False)
db = client[MONGO_DB] # 抓取索引
def get_page_index(offset,keyword):
# 构造请求数据信息
data ={
'office':offset, # 默认页码
'format': 'json', # 数据格式
'keyword': 'keyword', # 关键字
'autoload': 'true',
'count': '20',
'cur_tab': 3,
}
url = 'http://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(html):
try:
data = json.loads(html)
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 RequestException:
print('请求详情页出错',url)
print(url) def parse_page_detail(html,url):
soup = BeautifulSoup(html,'lxml')
title = soup.select('title')[0].get_text()
print(title)
images_pattern = re.compile('var gallery = (.*?)',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_image(image)
return {
'title':title,
'url':url,
'images':images, } def save_to_monogo(result):
if db[MONGO_TABLE].insert(result):
print('存储到MonogoDB成功',result)
return True
return False def download_image(url):
print('正在下载',url)
try:
response = requests.get(url)
if response.status_code == 200:
# return response.text
save_image(response.content)
return None
except RequestException:
print('请求图片出错出错',url)
return None def save_image(content):
file_path = '{0}/{1}.{2}'.format(ls.getcwd(),md5(content).hexdigest(),'jpg')
if not os.path.exists(file_path):
with open(file_path,'wb') as f:
f.writable(content)
f.close() def main(offset):
# html = get_page_index(0,'街拍')
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 result: save_to_monogo(result) print(result)
if __name__ == '__main__':
# main()
groups = [x*20 for x in range(GROUP_START,GROUP_END + 1)]
pool = Pool()
pool.map(main, groups)
python AjaxSpider 代码演示的更多相关文章
- python 类继承演示范例的代码
把做工程过程重要的代码片段备份一次,下面的资料是关于python 类继承演示范例的代码. # a simple example of a class inheritance # tested with ...
- Python Web框架Tornado的异步处理代码演示样例
1. What is Tornado Tornado是一个轻量级但高性能的Python web框架,与还有一个流行的Python web框架Django相比.tornado不提供操作数据库的ORM接口 ...
- 代码演示C#各版本新功能
代码演示C#各版本新功能 C#各版本新功能其实都能在官网搜到,但很少有人整理在一起,并通过非常简短的代码将每个新特性演示出来. 代码演示C#各版本新功能 C# 2.0版 - 2005 泛型 分部类型 ...
- Python一行代码
1:Python一行代码画出爱心 print]+(y*-)**-(x**(y*<= ,)]),-,-)]) 2:终端路径切换到某文件夹下,键入: python -m SimpleHTTPServ ...
- python爬虫代码
原创python爬虫代码 主要用到urllib2.BeautifulSoup模块 #encoding=utf-8 import re import requests import urllib2 im ...
- 14种网页jQuery和css3特效插件代码演示
1.网页table增删样式代码 演示和下载地址 2.jQuery左右滑动幻灯片插件 演示和下载地址 3.jQuery文字轮播焦点图 演示和下载地址 4.网页文字焦点图切换 演示和下载地址 5.jQue ...
- 9种jQuery和css3图片动画特效代码演示
1.自由旋转的jQuery图片 演示和下载地址 2.css3阴影动画效果 演示和下载地址 3.拉窗帘特效图片 演示和下载地址 4.css3文字特效动画 演示和下载地址 5.css3时钟代码 演示和下载 ...
- java 覆盖hashCode()深入探讨 代码演示样例
java 翻盖hashCode()深入探讨 代码演示样例 package org.rui.collection2.hashcode; /** * 覆盖hashcode * 设计HashCode时最重要 ...
- javascript 压缩空格代码演示
压缩空格代码演示 主要是讲解 压缩一个字符串两段空格 例如:javascript函数里的空格不论是这样 var s = "Hello World ...
随机推荐
- OpenCV调整彩色图像的饱和度和亮度
问题 如何调整彩色图像的饱和度和亮度 解决思路 详细步骤: 将RGB图像值归一化到[0, 1] 然后使用函数cvtColor进行色彩空间的转换 接下来可以根据处理灰度图像对比度增强伽马变换或者线性变换 ...
- Netty源码分析(前言, 概述及目录)
Netty源码分析(完整版) 前言 前段时间公司准备改造redis的客户端, 原生的客户端是阻塞式链接, 并且链接池初始化的链接数并不高, 高并发场景会有获取不到连接的尴尬, 所以考虑了用netty长 ...
- DevOps架构下如何进行微服务性能测试?
一. 微服务架构下的性能测试挑战 微服务与DevOps 微服务是实现DevOps的重要架构 微服务3S原则 DevOps核心点 微服务架构下的业务特点 亿级用户的平台 单服务业务随时扩容 服务之间存在 ...
- Alpha阶段个人贡献分及转会人员确定
请各个团队协商确定个人贡献分,评分根据之前个团队确定的规则进行.每个团队的个人贡献分总数为50*N,N为团队的人数. 个人贡献分要求:必须是一个自然数,每个人分数互不相同,并且和为50*N. 请各个团 ...
- ElasticSearch 2 (21) - 语言处理系列之单词识别
ElasticSearch 2 (21) - 语言处理系列之单词识别 摘要 一个英语单词相对容易识别:因为英语单词是被空格或(某些)标点符号隔开的.但在英语中也有反例:you're 这个词是一个单词还 ...
- Windows下PyInstaller的使用教程
直接使用Python开发的软件时有许多不方便的地方,如需要安装特定的Python环境,需要安装依赖库.为了便于部署,需要将Python源代码编译成可执行文件,编译后的可执行文件就能脱离python环境 ...
- Linux命令(十四) 查看工作目录文件 ls
目录 1.命令简介 2.常用参数介绍 3.实例 4.直达底部 命令简介 ls 命令是 Linux 下最常用的命令. ls 就是 list 的缩写.默认情况下 ls 命令用来打印出当前目录的清单, 如果 ...
- 浅谈JavaSript中的this
JavaScript的this对初学者来说一直是一个很头疼的问题,因为它的指向刚刚接触的时候往往觉得有点莫名奇妙,这篇博客用实例来概括一下,this代表什么以及如何改变函数的this. 在<Ja ...
- bzoj1214 [HNOI2004]FTP服务器
题目挺复杂的. 但有一点好,就是这题没数据,交个空程序就好了. begin end.
- JDK7新特性try-with-resources语句
try-with-resources语句是一种声明了一种或多种资源的try语句.资源是指在程序用完了之后必须要关闭的对象.try-with-resources语句保证了每个声明了的资源在语句结束的时候 ...