Python3 爬虫基础系列教程(亲测有效)

来源:互联网 发布:怎么解析服务器域名 编辑:程序博客网 时间:2024/05/18 00:20

前言:前些天有个学长跟我说,有个项目是关于Python爬虫的。我本来打算大三的时候在开始学的。既然,现在有需要那就从现在开始学习。之前我是从没有接触过Python,大概了花了一个月的时间接触。了解了下,基本语法。由于大一大二一直学习PHP,所以能够很快的入门。可是自己还是很困惑,不知道用Python写成一个网站都怎么样。有疑惑就好解决,于是就百度谷歌,后来知道有DJango框架,于是又花了点时间了解了下它。终于知道整个的处理机制。



下面就是学习写爬虫代码了,发现网上好多都是Python2.7 版本的教程,自己也搜了好半天,后来决定自己写个3 的教程。共同记录下学习的过程。



好了直接上3 的代码吧。由于已经存在好多p 2.7 的教程,所以我就直接把不同点分享出来

import urllib.requestimport urllib.errorpage = 1url='http://www.qiushibaike.com/hot/page/' + str(page)user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'headers = {'User-Agent' : user_agent }try:    request = urllib.request.Request(url,headers = headers)    response = urllib.request.urlopen(request)    print(response.read())except urllib.error.HTTPError as e:    if hasattr(e,"code"):        print(e.code)    if hasattr(e,"reason"):        print(e.reason)

出现下面和URL链接页面的源代码一样的就说明成功了。


接下来继续:

import urllib.requestimport urllib.errorimport repage = 1url='http://www.qiushibaike.com/hot/page/' + str(page)user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'headers = {'User-Agent' : user_agent }try:    request = urllib.request.Request(url,headers = headers)    response = urllib.request.urlopen(request)    content = response.read().decode('utf-8')    pattern =re.compile('<div class=""hor">.*?<a. *?<img.*?>(.*?)</a>',re.S)    items = re.findall(pattern,content)    for item in items:        print(item[0],item[1])except urllib.error.HTTPError as e:    if hasattr(e,"code"):        print(e.code)    if hasattr(e,"reason"):        print(e.reason)


~                        
是抓取糗事百科的页面,具体的正则按照自己的需要来

原创粉丝点击