简单的python爬虫——贴吧上取邮箱

来源:互联网 发布:糠秕孢子菌毛囊炎 知乎 编辑:程序博客网 时间:2024/06/07 07:03

这是一个比较简单的爬虫,只用到了两个简单的库re和urllib,
程序使用的是python2.7
urllib模块是用来获取原文网页,
re模块是用来匹配特定的字符的,
1.获取链接的最后一页

html = urllib.urlopen(url).read()reyuan = r'<a href=".*?pn=(.*?)">尾页</a>'recom = re.compile(reyuan)refind = re.findall(recom,html)

注意事项:设置编码类型为utf-8,如果定义gb2312,不能获取到网页的尾页,这是字符编码的问题,python3中就没有这样的问题
2.逐页遍历,获得邮箱

a = 尾页数#由上面的代码得到while i<=int(a):        content = urllib.urlopen(url+str(i)).read()        print("现在在下载第"+str(i)+"页,总共"+str(a) +"页")        i += 1        pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}'        items =re.findall(pattern,content)        for item in items:           print item

注意事项:如果按照上面输出的是乱码可以这么写

 print("现在在下载第".decode("utf-8").encode("gb2312")+str(i)+"页,总共".decode("utf-8").encode("gb2312")+str(get_ye(url)) +"页".decode("utf-8").encode("gb2312"))        i += 1

3.将邮箱保存到文件中

file = open("E:\\python\\qqcom1.txt","w+")file.write(item+ '\n')file.close()

注意事项:记得最后关闭文件

4.整理代码

#coding:utf-8import urllibimport refile = open("E:\\python\\qqcom1.txt","w+")url = "http://tieba.baidu.com/p/4194772383?pn="def get_ye(url):    html = urllib.urlopen(url).read()    reyuan = r'<a href=".*?pn=(.*?)">尾页</a>'    recom = re.compile(reyuan)    refind = re.findall(recom,html)    return refind[0]def get_qq():    i = 1    j = 1    while i<=int(get_ye(url)):        content = urllib.urlopen(url+str(i)).read()        print("现在在下载第"+str(i)+"页,总共"+str(get_ye(url)) +"页")        i += 1        pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}'        items =re.findall(pattern,content)        for item in items:            file.write(item+ '\n')            j += 1    else:        print "结束"        file.write(str(j)+ '\n')        print j        file.close()if __name__=="__main__":    get_qq()

如果输出乱码就可以在每个字符串后面加上decode(“utf-8”).encode(“gb2312”)就可以了

( 写于2015年12月16日,http://blog.csdn.net/bzd_111)

0 0
原创粉丝点击