自然语言处理中,第一步通常是获取各种文本数据,而当前获取各种html网页是最基本的方式,在python中通常使用urllib2或者urllib3进行获取,但是这些python模块会涉及一些http请求的细节性问题不便于使用,一直替换方式是使用python的pycurl模块,以下是一个使用pycurl模块获取html源代码的实例程序,其基本流程如下:
1.设置URL
2.如果有如301或者302的转向,允许继续获取新地址的源代码
3.设置连接超时时间
4.返回源代码内容
#-*- coding: UTF-8 -*- import pycurl try: from io import BytesIO except ImportError: from StringIO import StringIO as BytesIO def getHtml(url): buffer = BytesIO() c = pycurl.Curl() c.setopt(c.URL, url) # Follow redirect. c.setopt(c.FOLLOWLOCATION, True) c.setopt(c.TIMEOUT, 15) c.perform() # HTTP response code, e.g. 200. print('Status: %d' % c.getinfo(c.RESPONSE_CODE)) # Elapsed time for the transfer. print('Status: %f' % c.getinfo(c.TOTAL_TIME)) # getinfo must be called before close. c.close() body = buffer.getvalue() return body url ='http://zhilun.me' content = getHtml(url) print content
当然该程序还有很多细节没有完成,例如:获取的html源代码其编码和我们本地系统的编码不一致,因此需要去获取源代码的编码方式进行转码;将获取的html源代码写入文件或者入库;清除一些非必要的html内容,比如图片标签、js代码、css代码,iframe代码等等。
这篇文章还没有评论