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

来源:互联网 发布:淘宝店如何上架宝贝 编辑:程序博客网 时间:2024/04/24 23:18

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 requestsfrom bs4 import BeautifulSoupdef 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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

4. 实现效果

糗事百科
这里写图片描述

阅读全文
0 0
原创粉丝点击