python爬虫开发之使用python爬虫库requests,urllib与今日头条搜索功能爬取搜索内容实例


Posted in Python onMarch 10, 2020

使用python爬虫库requests,urllib爬取今日头条街拍美图

代码均有注释

import re,json,requests,os
from hashlib import md5
from urllib.parse import urlencode
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
from multiprocessing import Pool
#请求索引页
def get_page_index(offset,keyword):
  #传送的数据
  data={
    'offset': offset,
    'format': 'json',
    'keyword': keyword,
    'autoload': 'true',
    'count': '20',
    'cur_tab': 1
  }
  #自动编码为服务器可识别的url
  url="https://www.toutiao.com/search_content/?"+urlencode(data)
  #异常处理
  try:
    #获取返回的网页
    response=requests.get(url)
    #判断网页的状态码是否正常获取
    if response.status_code==200:
      #返回解码后的网页
      return response.text
    #不正常获取,返回None
    return None
  except RequestException:
    #提示信息
    print("请求索引页出错")
    return None
#解析请求的索引网页数据
def parse_page_index(html):
  #json加载转换
  data=json.loads(html)
  #数据为真,并且data键值存在与数据中
  if data and 'data' in data.keys():
    #遍历返回图集所在的url
    for item in data.get('data'):
      yield item.get('article_url')
#图集详情页请求
def get_page_detail(url):
  #设置UA,模拟浏览器正常访问
  head = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
  #异常处理
  try:
    response=requests.get(url,headers=head)
    if response.status_code==200:
      return response.text
    return None
  except RequestException:
    print("请求详情页出错")
    return None
#解析图集详情页的数据
def parse_page_detail(html,url):
  #异常处理
  try:
    #格式转换与图集标题提取
    soup=BeautifulSoup(html,'lxml')
    title=soup.select('title')[0].get_text()
    print(title)
    #正则查找图集链接
    image_pattern = re.compile('gallery: (.*?),\n', re.S)
    result = re.search(image_pattern, html)
    if result:
      #数据的优化
      result=result.group(1)
      result = result[12:]
      result = result[:-2]
      #替换
      result = re.sub(r'\\', '', result)
      #json加载
      data = json.loads(result)
      #判断数据不为空,并确保sub——images在其中
      if data and 'sub_images' in data.keys():
        #sub_images数据提取
        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
        }
  except Exception:
    pass
#图片url请求
def download_images(url):
  #提示信息
  print('正在下载',url)
  #浏览器模拟
  head = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
  #异常处理
  try:
    response = requests.get(url, headers=head)
    if response.status_code == 200:
      #图片保存
      save_image(response.content)
    return None
  except RequestException:
    print("请求图片出错")
    return None
#图片保存
def save_image(content):
  #判断文件夹是否存在,不存在则创建
  if '街拍' not in os.listdir():
    os.makedirs('街拍')
  #设置写入文件所在文件夹位置
  os.chdir('E:\python写网路爬虫\CSDN爬虫学习\街拍')
  #路径,名称,后缀
  file_path='{0}/{1}.{2}'.format(os.getcwd(),md5(content).hexdigest(),'jpg')
  #图片保存
  with open(file_path,'wb') as f:
      f.write(content)
      f.close()
#主函数
def mian(offset):
  #网页获取
  html=get_page_index(offset,'街拍')
  #图集url
  for url in parse_page_index(html):
    if url!=None:
      #图集网页详情
      html=get_page_detail(url)
      #图集内容
      result=parse_page_detail(html,url)
if __name__ == '__main__':
  #创建访问的列表(0-9)页
  group=[i*10 for i in range(10)]
  #创建多线程进程池
  pool=Pool()
  #进程池启动,传入的数据
  pool.map(mian,group)

爬取图片如下

python爬虫开发之使用python爬虫库requests,urllib与今日头条搜索功能爬取搜索内容实例

本文主要讲解了python爬虫库requests、urllib与OS模块结合使用爬取今日头条搜索内容的实例,更多关于python爬虫相关知识请查看下面的相关链接

Python 相关文章推荐
python 文件与目录操作
Dec 24 Python
python抓取某汽车网数据解析html存入excel示例
Dec 04 Python
Python中super()函数简介及用法分享
Jul 11 Python
使用Python读取大文件的方法
Feb 11 Python
Python使用min、max函数查找二维数据矩阵中最小、最大值的方法
May 15 Python
Flask核心机制之上下文源码剖析
Dec 25 Python
python实现AES加密与解密
Mar 28 Python
Python Pandas 获取列匹配特定值的行的索引问题
Jul 01 Python
django-allauth入门学习和使用详解
Jul 03 Python
Django框架ORM数据库操作实例详解
Nov 07 Python
Python爬虫之爬取淘女郎照片示例详解
Jul 28 Python
python gui开发——制作抖音无水印视频下载工具(附源码)
Feb 07 Python
python+gdal+遥感图像拼接(mosaic)的实例
Mar 10 #Python
python获取栅格点和面值的实现
Mar 10 #Python
Python列表切片常用操作实例解析
Mar 10 #Python
Python numpy多维数组实现原理详解
Mar 10 #Python
python中使用you-get库批量在线下载bilibili视频的教程
Mar 10 #Python
Python字符串hashlib加密模块使用案例
Mar 10 #Python
Python中求对数方法总结
Mar 10 #Python
You might like
Cannot modify header information错误解决方法
2008/10/08 PHP
header导出Excel应用示例
2014/01/24 PHP
百度地图API应用之获取用户的具体位置
2014/06/10 PHP
php表单提交实例讲解
2015/11/12 PHP
基于jquery的设置页面文本框 只能输入数字的实现代码
2011/04/19 Javascript
同一个网页中实现多个JavaScript特效的方法
2015/02/02 Javascript
Vuex模块化实现待办事项的状态管理
2017/03/15 Javascript
简单好用的nodejs 爬虫框架分享
2017/03/26 NodeJs
js,jq,css多方面实现简易下拉菜单功能
2017/05/13 Javascript
使用Vue制作图片轮播组件思路详解
2018/03/21 Javascript
vue学习笔记五:在vue项目里面使用引入公共方法详解
2019/04/04 Javascript
vuejs移动端实现div拖拽移动
2019/07/25 Javascript
js实现图片粘贴到网页
2019/12/06 Javascript
Python用threading实现多线程详解
2017/02/03 Python
wxPython的安装与使用教程
2018/08/31 Python
对python 命令的-u参数详解
2018/12/03 Python
Python进程间通信 multiProcessing Queue队列实现详解
2019/09/23 Python
PyCharm2020.1.2社区版安装,配置及使用教程详解(Windows)
2020/08/07 Python
韩国邮政旗下生鲜食品网上超市:epost
2016/08/27 全球购物
Saks Fifth Avenue澳洲/亚太地区:萨克斯第五大道精品百货店
2019/06/09 全球购物
迪卡侬波兰体育用品商店:Decathlon波兰
2020/03/31 全球购物
求职简历中个人的自我评价
2013/12/01 职场文书
音乐教学反思
2014/02/02 职场文书
采购助理岗位职责
2014/02/16 职场文书
工会趣味活动方案
2014/08/18 职场文书
授权委托书范本(单位)
2014/09/28 职场文书
乡镇党的群众路线教育实践活动个人整改方案
2014/10/31 职场文书
捐款通知怎么写
2015/04/24 职场文书
导游带团欢迎词
2015/09/30 职场文书
2016年第32个教师节红领巾广播稿
2015/12/18 职场文书
Mysql数据库命令大全
2021/05/26 MySQL
springboot @ConfigurationProperties和@PropertySource的区别
2021/06/11 Java/Android
Python爬虫框架之Scrapy中Spider的用法
2021/06/28 Python
Apache Linkis 中间件架构及快速安装步骤
2022/03/16 Servers
golang语言指针操作
2022/04/14 Golang
Go gorilla securecookie库的安装使用详解
2022/08/14 Golang