您的位置:首页 > 编程语言 > Python开发

python抓页面基础知识

2016-10-11 17:30 260 查看
python抓页面基础知识

1.定义函数根据url获得页面

 def getPageContent(self,url):

        request = urllib2.Request(url)

        response = urllib2.urlopen(request)

        return response.read().decode('UTF-8')

2. 正则表达式匹配,re.S是dotall模式,意思是.表示所有字符的意思包括换行,()是分组的意思

pattern = re.compile('<div class="d_author">.*?<ul class="p_author">.*?'+

                              '<li class="d_name".*?<a.*?'+

                              'target="_blank">(.*?)</a>',re.S)

content = re.findall(pattern, pagecontent)

3.第二步中的content是数组,通过循环将数据写到文件,item是tuple类型使用[]使用,item[0]为第一列数据,item[1]为第二列,以此类推。

f = open('1.txt','a+')

for item in content:
f.writelines((str(item[0])+str(item[1])+item[2].encode('UTF-8'),f)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息