学习Python之网络爬虫(一)

来源:互联网 发布:java urlencode 加号 编辑:程序博客网 时间:2024/03/29 15:01

     因为近期在学习神经网络和深度学习方面的内容,需要使用Python进行编程学习。因为之前没有学习过Python,所以就需要抓紧学起来,想要学的东西好多啊!!!

    近期通过网上的一些教程来学习Python,学习网络爬虫。本篇文章主要是讲如何抓取新浪博客中黄健翔的首页中的文章。

1.Python.exe的安装

   目前有两大版本——Python 2 && Python 3 。Python 3 的语法规则相比较 Python 2 有些许不同,我会在Python 2中现将其功能实现,再将其移植到Python 3 运行环境中。

本篇文章的网络爬虫使用的是Python 2。


2.写第一个Python程序——给定文章地址,抓取文章

2.1 首先要了解新浪博客的html语言风格,使用chrome浏览器,按【F12】就可以看到相应网页的源码信息,然后找到我们需要抓取的文章的地址,如下图所示。

                                                                                                            图1 需要下载的第一篇文章列表和相应的html信息

2.2 编写Python 代码

#!/usr/bin/python27import urllib  str0 = '<a title="" target="_blank" href="http://blog.sina.com.cn/s/blog_5137be260102e89z.html">我的人生就是一次次世界杯串起来的</a>'title = str0.find(r'<a title=')     #find -> 从字符串中找‘’内中的内容,返回这个字符串中的第几个数据位href  = str0.find(r'href=',title)html  = str0.find(r'html',href)url   = str0[href + 6 : html + 4]   #列表list 索引到地址的内容print (url)content = urllib.urlopen(url).read()  #读操作#print (content)open(r'huangjianxiang/'+url[-26:],'wb+').write(content)  #写操作 就可以将读到的url中的内容写到这个文件中了print ('downloading',url)

3.难度递进——抓取博客列表中第一页的所有文章


        

图2 需要下载的所有文章列表和相应的html信息

#!/usr/bin/python27#coding:utf-8import urllibimport timei = 0url = ['']*50webpage = urllib.urlopen('http://blog.sina.com.cn/s/articlelist_1362607654_0_1.html').read()##寻找列表中的文章title = webpage.find(r'<a title=')href  = webpage.find(r'href=',title)html  = webpage.find(r'html',href)while title != -1 and href != -1 and html != -1 and i < 50 : url[i] = webpage[href + 6 : html + 4] print (url[i]) title = webpage.find(r'<a title=',html) href  = webpage.find(r'href=',title) html  = webpage.find(r'html',href) i += 1else:    print ('find end!')     #将文章地址依次下载下来j = 0while j < 50: content = urllib.urlopen(url[j]).read() open(r'huangjianxiang/'+url[j][-26:],'w+').write(content) print ('downloading',url[j]) j += 1 time.sleep(15)else:    print ('download end!')

这样就可以把黄健翔新浪博客首页的所有文章依次下载下来,这里主要是对数组和while循环的学习和使用。


3.难度递进——抓取网页中部分信息(未完待续..............)

1 0