demo
- 此demo用于实现获取指定页面的所有超链接
import re
import urllib
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def getImg(html):
reg = r'(?<=href\=\")(.*?)(?=\")' // 定义一个正则表达式字符串里面的所有字符都不会被转义
imgre = re.compile(reg) // 转为正则表达式对象
imglist = re.findall(imgre,html) // 搜索string
return imglist
html = getHtml("http://www.jianshu.com/u/6703a40d0b77")
print getImg(html)
说明:
python正则表达式模块re:
这里有介绍https://gist.github.com/rswofxd/2787060核心模块urllib:
用于访问不需要验证的网络资源,提供urlopen(创建一个表示远程url的类文件对象)及urlretrieve(直接将远程数据下载到本地)等方法。r 开头的python字符串:
raw 字符串,所以里面的所有字符都不会被转义。re.compile
可以把正则表达式编译成一个正则表达式对象。可以把那些经常使用的正则表达式编译成正则表达式对象,这样可以提高一定的效率。re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。
运行:
1.在linux下安装python(略);
-
2.保存上文代码,执行
$python yourFileName.py