您的位置:首页 > 编程语言 > Python开发

python学习笔记(3)--爬虫基础教程1

2016-11-07 11:46 711 查看
[align=center]Python学习笔记(3)-爬虫基础教程(1)[/align] 参考网页:【1】.爬虫:http://www.cnblogs.com/fnng/p/3576154.html
                  【2】.正则表达式:http://www.cnblogs.com/fnng/p/3576154.html
                  【3】.《Python爬虫学习系列教程》学习笔记  http://www.cnblogs.com/xin-xin/p/4297852.html

 功能实现:从“糗事百科”上爬段子和作者#Python版本:3.4.2#和先前版本不一样的地方 1)print 后内容要加括号
 2)except urllib2.URLError as e:这句在之前的版本中‘as’是由','代替的 

 Step 1 :

      import re      import urllib.request as urllib2    #在Python 3.X后urllib2变成了urllib.request,为了方便使用,就定义一个urllib2来代替
 

 Step 2:获取页面信息:

 
      url = 'http://www.qiushibaike.com/'                                                             #URL(统一资源定位符)信息      user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) '                            #加一个header,否则访问不成功
      #header信息获取方式(谷歌浏览器):  自定义及控制--->更多工具--->开发者工具--->Network---->.....   

     
#header验证部分,如果成功了就打印BEGIN  
    headers = { 'User-Agent' : user_agent }                                                          try:            request = urllib2.Request(url,headers = headers)            response = urllib2.urlopen(request)            print ('BEGIN')     except urllib2.URLError as e:            if hasattr(e,"code"):                print ('aaa')           if hasattr(e,"reason"):               print ('bbb')       


Step 3.  用正则表达式筛选要爬下来的东西

content = response.read().decode('utf-8')                                #解码方式是utf-8


 
#这句正则表达式的两个(.*?)内分别是作者和内容,正则表达式参照日志开头参考网页【2】
#re.S表示多行匹配
pattern = re.compile('<h2>(.*?)</h2></a></div><div .*?"content">(.*?)<!--(.*?)--></div>',re.S)
  #将所有爬到的东西存在items中  items = re.findall(pattern,content)

4. 查看items中的东西

x=1 for item in items:  print(x)  print("author:")  print (item[0])     #item[0]中是作者  print("story:")  print(item[1])    #item[1]中是段子  x=x+1 

#结果截图 


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: