码迷,mamicode.com
首页 > 编程语言 > 详细

Python爬虫_用Python爬取csdn页面信息目录

时间:2015-05-19 10:44:32      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:python   爬虫   python获取csdn信息   爬csdn   python爬虫   

1.原理:

这个程序可以实现批量获取到某一个CSDN博客的个人信息、目录与链接的对应,并存到一个本目录的mulu.txt文件中

2.具体代码:

# -*- coding: cp936 -*-
import urllib.request#
import re#
import sys#
import time#
import random
import string
headers = {#
    'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'  
}
url_end=[]#
title_end=[]
for n in range(2):
    req = urllib.request.Request(
        url = 'http://blog.csdn.net/wangquannetwork/article/list/'+str((n+1)),
        headers = headers
    )
    content = urllib.request.urlopen(req).read()
    content = content.decode('utf-8')
    p=re.compile('\r\n')
    content=re.sub(p,'',content)

    url_str = re.findall('((?<=(link_title\"><a href=\")).*?(?=\"))',content)
    for i in range(len(url_str)):
        url_end.append('blog.csdn.net'+url_str[i][0])

    title_str = re.findall('((?<=([0-9][0-9][0-9][0-9][0-9]\">)).*?(?=(</a></span>)))',content)
    for i in range(len(title_str)):
        title_end.append(title_str[i][0][8:])

content = urllib.request.urlopen(req).read()
content = content.decode('utf-8')
span_str = re.findall(r'(?<=<li>).+?(?=</li>)',content)
title_str = re.findall(r'(((?<=(k\">)).*?(?=(</a>))))',content)

sName='./mulu.txt'
with open(sName,'w') as file:
    file.write('这是 '+title_str[0][0]+' 的博客')
    file.write('\n')
    file.write('下面是博客信息')
    file.write('\n')
    for x in range(0,5):  
        file.write(span_str[x])
        file.write('\n')
    file.write('\n')
    file.write('一共有'+str(len(url_end))+'个文章')
    file.write('\n')
    file.write('\n')
    for i in range(len(url_end)):
        file.write(str((i+1))+'.')
        file.write(title_end[i])
        file.write('\n')
        file.write(url_end[i])
        file.write('\n')



3.Python代码实现结果:

技术分享


注意:以上内容均为原创作品 转载请注明出处http://blog.csdn.net/wangquannetwork/article/details/45832109


Python爬虫_用Python爬取csdn页面信息目录

标签:python   爬虫   python获取csdn信息   爬csdn   python爬虫   

原文地址:http://blog.csdn.net/wangquannetwork/article/details/45832109

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!