使用requests+beautifulsoup模块实现python网络爬虫功能

1. 前言

之前实现python的网络爬虫, 主要都是使用较为底层的urllib, urllib2 实现的, 这种实现方案显得比较原始, 编码起来也比较费劲, 尤其是提取信息的时候, 还得使用正则表达是匹配 (之前转载的一篇糗事百科的爬虫文章, http://blog.csdn.net/zhyh1435589631/article/details/51296734)。 我们这里采用requests + beautifulsoup 的实现方案, 使用 css 选择器, 简化代码的书写。

2. 基本资料

  1. 当然在使用这两个模块之前, 需要对这两个模块做一些介绍:
    requests 主要是一个封装好了http功能的库, 可以实现基本的http操作
    beautifulsoup 主要提供了对html, xml网页的一个完美的解析方式, 实际上, 他将html中的tag 作为树节点进行解析, 于是, 我们可以将一个html页面看成是一颗树结构。
  2. requests 官方文档: http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
  3. beautifulsoup 官方文档: https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

3. 实现代码

代码比较简洁, 就不多说了, 下面的代码中, 我们分别爬取两个网站, 糗事百科 和 我们学校的就业网站。

# -*- coding=utf8 -*-

import requests
from bs4 import BeautifulSoup

def qiushibaike():
    content = requests.get('http://www.qiushibaike.com').content
    soup = BeautifulSoup(content, 'html.parser')

    for div in soup.find_all('div', {'class' : 'content'}):
        print div.text.strip()

def ustcjob():
    headers = {'User-Agent':'Mozilla / 5.0(X11;Linux x86_64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 50.0.2661.102 Safari / 537.36'}
    content = requests.get('http://job.ustc.edu.cn/list.php?MenuID=002', headers = headers).content
    soup = BeautifulSoup(content, 'html.parser')

    for Jop in soup.find_all('div', {'class' : 'Joplistone'}):
        for item in Jop.find_all('li'):
            print "%-30s%-20s%-40s" % (item.a.text.strip() , item.span.text.strip() , item.span.next_sibling.text.strip())


if __name__ == '__main__':
    #qiushibaike()
    ustcjob()

4. 实现效果

糗事百科
这里写图片描述
学校就业网站招聘会信息
这里写图片描述

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值