python2.7实现爬虫网页数据


Posted in Python onMay 25, 2018

最近刚学习Python,做了个简单的爬虫,作为一个简单的demo希望帮助和我一样的初学者。

代码使用python2.7做的爬虫  抓取51job上面的职位名,公司名,薪资,发布时间等等。

直接上代码,代码中注释还算比较清楚 ,没有安装mysql需要屏蔽掉相关代码:

#!/usr/bin/python 
# -*- coding: UTF-8 -*- 
 
from bs4 import BeautifulSoup 
import urllib 
import urllib2 
import codecs 
import re 
import time 
import logging 
import MySQLdb 
 
 
class Jobs(object): 
 
  # 初始化 
  """docstring for Jobs""" 
 
  def __init__(self): 
    super(Jobs, self).__init__() 
     
    logging.basicConfig(level=logging.DEBUG, 
         format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') 
    #数据库的操作,没有mysql可以做屏蔽 
    self.db = MySQLdb.connect('127.0.0.1','root','rootroot','MySQL_Test',charset='utf8') 
    self.cursor = self.db.cursor() 
 
    #log日志的显示 
    self.logger = logging.getLogger("sjk") 
 
    self.logger.setLevel(level=logging.DEBUG) 
 
    formatter = logging.Formatter( 
      '%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
    handler = logging.FileHandler('log.txt') 
    handler.setFormatter(formatter) 
    handler.setLevel(logging.DEBUG) 
    self.logger.addHandler(handler) 
 
    self.logger.info('初始化完成') 
 
  # 模拟请求数据 
  def jobshtml(self, key, page='1'): 
    try: 
      self.logger.info('开始请求第' + page + '页') 
      #网页url 
      searchurl = "https://search.51job.com/list/040000,000000,0000,00,9,99,{key},2,{page}.html?lang=c&stype=&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&providesalary=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare=" 
 
      user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:59.0) Gecko/20100101 Firefox/59.0' 
      #设置请求头 
      header = {'User-Agent': user_agent, 'Host': 'search.51job.com', 
           'Referer': 'https://www.51job.com/'} 
      #拼接url 
      finalUrl = searchurl.format(key=key, page=page) 
       
      request = urllib2.Request(finalUrl, headers=header) 
 
      response = urllib2.urlopen(request) 
      #等待网页加载完成 
      time.sleep(3) 
      #gbk格式解码 
      info = response.read().decode('gbk') 
 
      self.logger.info('请求网页网页') 
 
      self.decodeHtml(info=info, key=key, page=page) 
 
    except urllib2.HTTPError as e: 
      print e.reason 
 
  # 解析网页数据 
  def decodeHtml(self, info, key, page): 
    self.logger.info('开始解析网页数据') 
    #BeautifulSoup 解析网页 
    soup = BeautifulSoup(info, 'html.parser') 
    #找到class = t1 t2 t3 t4 t5 的标签数据 
    ps = soup.find_all(attrs={"class": re.compile(r'^t[1-5].*')}) 
    #打开txt文件 a+ 代表追加 
    f = codecs.open(key + '.txt', 'a+', 'UTF-8') 
    #清除之前的数据信息 
    f.truncate() 
 
    f.write('\n------------' + page + '--------------\n') 
 
    count = 1 
 
    arr = [] 
    #做一些字符串的处理,形成数据格式  iOS开发工程师 有限公司 深圳-南山区 0.9-1.6万/月 05-16 
    for pi in ps: 
      spe = " " 
      finalstr = pi.getText().strip() 
      arr.append(finalstr) 
      if count % 5 == 0: 
        #每一条数据插入数据库,如果没有安装mysql 可以将当前行注释掉 
        self.connectMySQL(arr=arr) 
        arr = [] 
        spe = "\n" 
      writestr = finalstr + spe 
      count += 1 
      f.write(writestr) 
    f.close() 
     
    self.logger.info('解析完成') 
 
#数据库操作 没有安装mysql 可以屏蔽掉 
  def connectMySQL(self,arr): 
    work=arr[0] 
    company=arr[1] 
    place=arr[2] 
    salary=arr[3] 
    time=arr[4] 
 
    query = "select * from Jobs_tab where \ 
    company_name='%s' and work_name='%s' and work_place='%s' \ 
    and salary='%s' and time='%s'" %(company,work,place,salary,time) 
    self.cursor.execute(query) 
 
    queryresult = self.cursor.fetchall() 
    #数据库中不存在就插入数据 存在就可以更新数据 不过我这边没有写 
    if len(queryresult) > 0: 
      sql = "insert into Jobs_tab(work_name,company_name,work_place,salary\ 
          ,time) values('%s','%s','%s','%s','%s')" %(work,company,place,salary,time) 
       
      try: 
        self.cursor.execute(sql) 
        self.db.commit() 
         
      except Exception as e: 
        self.logger.info('写入数据库失败') 
     
 
  #模拟登陆 
  # def login(self): 
  #   data = {'action':'save','isread':'on','loginname':'18086514327','password':'kui4131sjk'} 
 
 
  # 开始抓取 主函数 
  def run(self, key): 
 
    # 只要前5页的数据 key代表搜索工做类型 这边我是用的ios page是页数 
    for x in xrange(1, 6): 
      self.jobshtml(key=key, page=str(x)) 
 
    self.logger.info('写入数据库完成') 
 
    self.db.close() 
 
if __name__ == '__main__': 
 
  Jobs().run(key='iOS')

这样抓取网页数据格式如下:

python2.7实现爬虫网页数据

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
详解Django框架中的视图级缓存
Jul 23 Python
Python随机函数random()使用方法小结
Apr 29 Python
python3读取csv和xlsx文件的实例
Jun 22 Python
对sklearn的使用之数据集的拆分与训练详解(python3.6)
Dec 14 Python
对Python捕获控制台输出流的方法详解
Jan 07 Python
Python设计模式之组合模式原理与用法实例分析
Jan 11 Python
使用celery执行Django串行异步任务的方法步骤
Jun 06 Python
如何在Windows中安装多个python解释器
Jun 16 Python
浅谈Keras参数 input_shape、input_dim和input_length用法
Jun 29 Python
Python利用matplotlib绘制折线图的新手教程
Nov 05 Python
解决Python中的modf()函数取小数部分不准确问题
May 28 Python
Python按顺序遍历并读取文件夹中文件
Apr 29 Python
python sys.argv[]用法实例详解
May 25 #Python
python切片及sys.argv[]用法详解
May 25 #Python
windows下python安装pip图文教程
May 25 #Python
python3.6使用pymysql连接Mysql数据库
May 25 #Python
python matplotlib绘图,修改坐标轴刻度为文字的实例
May 25 #Python
Python二叉树定义与遍历方法实例分析
May 25 #Python
matplotlib 纵坐标轴显示数据值的实例
May 25 #Python
You might like
PHP删除数组中的特定元素的代码
2012/06/28 PHP
基于命令行执行带参数的php脚本并取得参数的方法
2016/01/25 PHP
Laravel执行migrate命令提示:No such file or directory的解决方法
2016/03/16 PHP
PHP cURL获取微信公众号access_token的实例
2018/04/28 PHP
JavaScript Distilled 基础知识与函数
2010/04/07 Javascript
jQuery获取iframe的document对象的方法
2014/10/10 Javascript
node.js中的console.warn方法使用说明
2014/12/09 Javascript
jquery实现聚光灯效果的方法
2015/02/06 Javascript
Vue.js每天必学之过滤器与自定义过滤器
2016/09/07 Javascript
jQuery根据ID、CLASS、等获取对象的实例
2016/12/04 Javascript
vue实现ajax滚动下拉加载,同时具有loading效果(推荐)
2017/01/11 Javascript
Vue中img的src属性绑定与static文件夹实例
2017/05/18 Javascript
详解基于node的前端项目编译时内存溢出问题
2017/08/01 Javascript
JS中常用的消息框总结
2018/02/24 Javascript
总结js函数相关知识点
2018/02/27 Javascript
npm配置国内镜像资源+淘宝镜像的方法
2018/09/07 Javascript
JS数组求和的常用方法实例小结
2019/01/07 Javascript
微信小程序学习总结(一)项目创建与目录结构分析
2020/06/04 Javascript
python使用urllib2模块获取gravatar头像实例
2013/12/18 Python
python读文件逐行处理的示例代码分享
2013/12/27 Python
Python安装第三方库及常见问题处理方法汇总
2016/09/13 Python
用Python写王者荣耀刷金币脚本
2017/12/21 Python
Python将DataFrame的某一列作为index的方法
2018/04/08 Python
django admin 后台实现三级联动的示例代码
2018/06/22 Python
python实现将json多行数据传入到mysql中使用
2019/12/31 Python
python二维图制作的实例代码
2020/12/03 Python
matplotlib交互式数据光标实现(mplcursors)
2021/01/13 Python
Elemis美国官网:英国的第一豪华护肤品牌
2018/03/15 全球购物
优秀社区干部事迹材料
2014/02/03 职场文书
优秀的2014年两会精神解读
2014/03/17 职场文书
2015教师节师德演讲稿
2015/03/19 职场文书
房地产财务经理岗位职责
2015/04/08 职场文书
离职信范文
2015/06/23 职场文书
银行中层干部培训心得体会
2016/01/11 职场文书
html输入两个数实现加减乘除功能
2021/07/01 HTML / CSS
动态规划之使用备忘录来改进Javascript函数
2022/04/07 Javascript