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 相关文章推荐
python通过pil将图片转换成黑白效果的方法
Mar 16 Python
python使用in操作符时元组和数组的区别分析
May 19 Python
python中sys.argv参数用法实例分析
May 20 Python
Python创建模块及模块导入的方法
May 27 Python
python去除空格和换行符的实现方法(推荐)
Jan 04 Python
解决python文件双击运行秒退的问题
Jun 24 Python
Python 占位符的使用方法详解
Jul 10 Python
python实现全排列代码(回溯、深度优先搜索)
Feb 26 Python
pycharm通过anaconda安装pyqt5的教程
Mar 24 Python
python利用Excel读取和存储测试数据完成接口自动化教程
Apr 30 Python
python 三边测量定位的实现代码
Apr 22 Python
django 认证类配置实现
Nov 11 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
第十二节--类的自动加载
2006/11/16 PHP
php md5下16位和32位的实现代码
2008/04/09 PHP
destoon安装出现Internal Server Error的解决方法
2014/06/21 PHP
百度工程师讲PHP函数的实现原理及性能分析(二)
2015/05/13 PHP
浅谈php错误提示及查错方法
2015/07/14 PHP
php模拟post上传图片实现代码
2016/06/24 PHP
PHP绕过open_basedir限制操作文件的方法
2018/06/10 PHP
JavaScript flash复制库类 Zero Clipboard
2011/01/17 Javascript
各情景下元素宽高的获取实现代码
2011/09/13 Javascript
js解析与序列化json数据(二)序列化探讨
2013/02/01 Javascript
JQuery对class属性的操作实现按钮开关效果
2013/10/11 Javascript
JQuery悬停控制图片轮播——代码简单
2015/08/05 Javascript
第十篇BootStrap轮播插件使用详解
2016/06/21 Javascript
javascript 网页进度条简单实例
2017/02/22 Javascript
JavaScript实现选中文字提示新浪微博分享效果
2017/06/15 Javascript
微信小程序图片选择区域裁剪实现方法
2017/12/02 Javascript
详解如何在vue项目中使用eslint+prettier格式化代码
2018/11/10 Javascript
微信小程序与后台PHP交互的方法实例分析
2018/12/10 Javascript
用Node写一条配置环境的指令
2019/11/14 Javascript
Python重新引入被覆盖的自带function
2014/07/16 Python
由Python运算π的值深入Python中科学计算的实现
2015/04/17 Python
详解python3中tkinter知识点
2018/06/21 Python
djano一对一、多对多、分页实例代码
2019/08/16 Python
win7下 python3.6 安装opencv 和 opencv-contrib-python解决 cv2.xfeatures2d.SIFT_create() 的问题
2019/10/24 Python
使用Python制作新型冠状病毒实时疫情图
2020/01/28 Python
eBay爱尔兰站:eBay.ie
2019/08/09 全球购物
泰国第一在线超市:Tops
2021/02/13 全球购物
高一物理教学反思
2014/01/24 职场文书
小学英语教学反思
2014/01/30 职场文书
党员“一帮一”活动总结
2015/05/07 职场文书
烈士陵园扫墓感想
2015/08/07 职场文书
积极心理学课程心得体会
2016/01/22 职场文书
员工升职自我评价
2019/03/26 职场文书
教你用Python爬取英雄联盟皮肤原画
2021/06/13 Python
详解Vue的列表渲染
2021/11/20 Vue.js
如何让你的Nginx支持分布式追踪详解
2022/07/07 Servers