zoukankan      html  css  js  c++  java
  • 初学爬虫(一)

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

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

    3. 实现代码
    代码比较简洁, 就不多说了, 下面的代码中, 我们分别爬取两个网站, 糗事百科 。
     1 # -*- coding=utf8 -*-
     2 
     3 import requests
     4 from bs4 import BeautifulSoup
     5 
     6 def qiushibaike():
     7     content = requests.get('http://www.qiushibaike.com').content
     8     soup = BeautifulSoup(content, 'html.parser')
     9 
    10     for div in soup.find_all('div', {'class' : 'content'}):
    11         print div.text.strip()
    12 
    13 def ustcjob():
    14     headers = {'User-Agent':'Mozilla / 5.0(X11;Linux x86_64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 50.0.2661.102 Safari / 537.36'}
    15     content = requests.get('http://job.ustc.edu.cn/list.php?MenuID=002', headers = headers).content
    16     soup = BeautifulSoup(content, 'html.parser')
    17 
    18     for Jop in soup.find_all('div', {'class' : 'Joplistone'}):
    19         for item in Jop.find_all('li'):
    20             print "%-30s%-20s%-40s" % (item.a.text.strip() , item.span.text.strip() , item.span.next_sibling.text.strip())
    21 
    22 
    23 if __name__ == '__main__':
    24     #qiushibaike()
    25     ustcjob()

    四.实现效果

     

  • 相关阅读:
    几种常用的曲线
    0188. Best Time to Buy and Sell Stock IV (H)
    0074. Search a 2D Matrix (M)
    0189. Rotate Array (E)
    0148. Sort List (M)
    0859. Buddy Strings (E)
    0316. Remove Duplicate Letters (M)
    0452. Minimum Number of Arrows to Burst Balloons (M)
    0449. Serialize and Deserialize BST (M)
    0704. Binary Search (E)
  • 原文地址:https://www.cnblogs.com/qq991025/p/11831776.html
Copyright © 2011-2022 走看看