python获取文本网页

来源:互联网 发布:乐视手机怎么改mac 编辑:程序博客网 时间:2024/06/06 00:30

        

Urllib 模块提供了读取web页面数据的接口,我们可以像读取本地文件一样读取wwwftp上的数据。首先,我们定义了一个getHtml()函数:

  urllib.urlopen()方法用于打开一个URL地址。

  read()方法用于读取URL上的数据,向getHtml()函数传递一个网址,并把整个页面下载下来。执行程序就会把整个网页打印输出。

代码如下:

#coding=utf-8

import urllib

import datetime

############################

#Function get the url source

#created 2017-02-18

############################

def getHtml(url):

    page = urllib.urlopen(url)

    html = page.read()

    return html

#**********************main*************#

#begin timestamp

now = datetime.datetime.now()

html = getHtml("http://hz.5i5j.com/")

#end timestamp

end = datetime.datetime.now()

inter = end-now

print inter

print html

#*****************************************#

#end


此外:re.compile()可以把正则表达式编译成一个正则表达式对象.

re.findall() 方法读取html中包含 imgre(正则表达式)的数据。

urllib.urlretrieve()方法,直接将远程数据下载到本地。

通过一个for循环对获取的图片连接进行遍历,为了使图片的文件名看上去更规范,对其进行重命名,命名规则通过x变量加1。保存的位置默认为程序的存放目录。


PS:如何获取时间

获取时间

import datetime

获得当前时间

now = datetime.datetime.now()  ->这是时间数组格式

转换为指定的格式:

otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S”)

直接相减可以求时间差。