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中使用base64模块处理字符编码的教程
Apr 28 Python
Python中super函数的用法
Nov 17 Python
怎么使用pipenv管理你的python项目
Mar 12 Python
利用python将json数据转换为csv格式的方法
Mar 22 Python
Python 一句话生成字母表的方法
Jan 02 Python
Python3实现定时任务的四种方式
Jun 03 Python
对Python中小整数对象池和大整数对象池的使用详解
Jul 09 Python
Python如何实现邮件功能
May 27 Python
简单了解Django项目应用创建过程
Jul 06 Python
在 Python 中使用 MQTT的方法
Aug 18 Python
python Tornado框架的使用示例
Oct 19 Python
python微信智能AI机器人实现多种支付方式
Apr 12 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
PHP的PSR规范中文版
2013/09/28 PHP
PHP中func_get_args(),func_get_arg(),func_num_args()的区别
2013/09/30 PHP
php 批量添加多行文本框textarea一行一个
2014/06/03 PHP
PHP中抽象类、接口的区别与选择分析
2016/03/29 PHP
PHPExcel导出2003和2007的excel文档功能示例
2017/01/04 PHP
phpStudy配置多站点多域名方法及遇到的403错误解决方法
2017/10/19 PHP
实例介绍PHP中zip_open()函数用法
2019/02/15 PHP
thinkphp5框架API token身份验证功能示例
2019/05/21 PHP
laravel-admin 在列表页添加自定义按钮的例子
2019/09/30 PHP
Laravel框架下的Contracts契约详解
2020/03/17 PHP
jQuery最佳实践完整篇
2011/08/20 Javascript
使用jsonp完美解决跨域问题
2014/11/27 Javascript
js+html5实现canvas绘制简单矩形的方法
2015/06/05 Javascript
javascript精确统计网站访问量实例代码
2015/12/19 Javascript
JS动态加载脚本并执行回调操作
2016/08/24 Javascript
Vue实例简单方法介绍
2017/01/20 Javascript
详解Koa中更方便简单发送响应的方式
2018/07/20 Javascript
在vue项目中正确使用iconfont的方法
2018/09/28 Javascript
微信小程序报错: thirdScriptError的错误问题
2020/06/19 Javascript
解决nuxt页面中mounted、created、watch执行两遍的问题
2020/11/05 Javascript
Python中实现字符串类型与字典类型相互转换的方法
2014/08/18 Python
用Python进行TCP网络编程的教程
2015/04/29 Python
Python抽象类的新写法
2015/06/18 Python
PyCharm设置SSH远程调试的方法
2018/07/17 Python
学生信息管理系统Python面向对象版
2019/01/30 Python
有关pycharm登录github时有的时候会报错connection reset的问题
2020/09/15 Python
使用CSS3编写类似iOS中的复选框及带开关的按钮
2016/04/11 HTML / CSS
美国新兴城市生活方式零售商:VILLA
2017/12/06 全球购物
JACK & JONES瑞典官方网站:杰克琼斯欧式风格男装
2017/12/23 全球购物
如何设置Java的运行环境
2013/04/05 面试题
用C#语言写出与SQLSERVER访问时的具体过程
2013/04/16 面试题
2014小学生国庆65周年演讲稿
2014/09/21 职场文书
个人遵守党的政治纪律情况对照检查材料
2014/09/26 职场文书
阿甘正传观后感
2015/06/01 职场文书
学会感恩主题班会
2015/08/12 职场文书
超市店长竞聘书
2015/09/15 职场文书