python爬虫案例——csdn数据采集

全栈工程师开发手册 (作者:栾鹏)
python教程全解

python爬虫案例——csdn数据采集

通过python实现csdn页面的内容采集是相对来说比较容易的,因为csdn不需要登陆,不需要cookie,也不需要设置header

本案例使用python实现csdn文章数据采集,获取我的博客下每篇文章的链接、标题、阅读数目。

需要安装BeautifulSoup包(点击下载

python包的安装方法请参考Python库的安装与卸载

python3.6下

#coding:utf-8
#本实例用于获取指定用户csdn的文章名称、连接、阅读数目
import urllib
import re
from bs4 import BeautifulSoup
#csdn不需要登陆,也不需要cookie,也不需要设置header
print('=======================csdn数据挖掘==========================')
urlstr="http://blog.csdn.net/luanpeng825485697?viewmode=contents"
host = "http://blog.csdn.net/luanpeng825485697"  #根目录

alllink=[urlstr]   #所有需要遍历的网址
data={}
def getdata(html,reg):  #从字符串中安装正则表达式获取值
    pattern = re.compile(reg)
    items = re.findall(pattern, html)
    for item in items:
        urlpath = urllib.parse.urljoin(urlstr,item[0])   #将相对地址,转化为绝对地址
        if not hasattr(object, urlpath):
            data[urlpath] = item
            print(urlpath,'     ', end=' ')  #python3中end表示结尾符,这里不换行
            print(item[2], '     ', end=' ')
            print(item[1])



#根据一个网址获取相关连接并添加到集合中
def getlink(url,html):
    soup = BeautifulSoup(html,'html5lib')   #使用html5lib解析,所以需要提前安装好html5lib包
    for tag in soup.find_all('a'):   #从文档中找到所有<a>标签的内容
        link = tag.get('href')
        newurl = urllib.parse.urljoin(url, link) #在指定网址中的连接的绝对连接
        if host not in newurl:  # 如果是站外连接,则放弃
            continue
        if newurl in alllink:   #不添加已经存在的网址
            continue
        if not "http://blog.csdn.net/luanpeng825485697/article/list" in newurl:  #自定义添加一些链接限制
            continue
        # if not "http://blog.csdn.net/luanpeng825485697/article/category/7060771" in newurl:  #必须是python类目下的列表
        #     continue
        # if not "http://blog.csdn.net/luanpeng825485697/article/category/7060770" in newurl:  # 必须是安卓类目下的列表
        #     continue
        alllink.append(newurl)   #将地址添加到链接集合中


#根据一个网址,获取该网址中符合指定正则表达式的内容
def craw(url):
    try:
        request = urllib.request.Request(url)  #创建一个请求
        response = urllib.request.urlopen(request)  #获取响应
        html = str(response.read(),'utf-8')  #读取返回html源码,,python2里面读取的是字节数组

        # reg = r'"link_title"><a href="(.*?)">\r\n(.*?)\n.*?</a>'  #只匹配文章地址和名称
        reg = r'"link_title"><a href="(.*?)">\r\n        (.*?)            \r\n.*?</a>[\s\S]*?阅读</a>\((.*?)\)</span>'  # 匹配地址、名称、阅读数目
        getdata(html,reg)
        getlink(url,html)

    except urllib.error.URLError as e:
        if hasattr(e,"code"):
            print(e.code)
        if hasattr(e,"reason"):
            print(e.reason)

for url in alllink:
    craw(url)

python2.7下

#coding:utf-8
#本实例用于获取指定用户csdn的文章名称、连接、阅读数目
import urllib2
import re
from bs4 import BeautifulSoup
#csdn不需要登陆,也不需要cookie,也不需要设置header
print('=======================csdn数据挖掘==========================')
urlstr="http://blog.csdn.net/luanpeng825485697?viewmode=contents"
host = "http://blog.csdn.net/luanpeng825485697"  #根目录

alllink=[urlstr]   #所有需要遍历的网址
data={}
def getdata(html,reg):  #从字符串中安装正则表达式获取值
    pattern = re.compile(reg)
    items = re.findall(pattern, html)
    for item in items:
        urlpath = urllib2.urlparse.urljoin(urlstr,item[0])   #将相对地址,转化为绝对地址
        if not hasattr(object, urlpath):
            data[urlpath] = item
            print urlpath,'     ',  #print最后有个逗号,表示输出不换行
            print item[2], '     ',
            print item[1]



#根据一个网址获取相关连接并添加到集合中
def getlink(url,html):
    soup = BeautifulSoup(html,'html.parser')   #使用html5lib解析,所以需要提前安装好html5lib包
    for tag in soup.find_all('a'):   #从文档中找到所有<a>标签的内容
        link = tag.get('href')
        newurl = urllib2.urlparse.urljoin(url, link) #在指定网址中的连接的绝对连接
        if host not in newurl:  # 如果是站外连接,则放弃
            continue
        if newurl in alllink:   #不添加已经存在的网址
            continue
        if not "http://blog.csdn.net/luanpeng825485697/article/list" in newurl:  #自定义添加一些链接限制
            continue
        alllink.append(newurl)   #将地址添加到链接集合中


#根据一个网址,获取该网址中符合指定正则表达式的内容
def craw(url):
    try:
        request = urllib2.Request(url)  #创建一个请求
        response = urllib2.urlopen(request)  #获取响应
        html = response.read()  #读取返回html源码
        # reg = r'"link_title"><a href="(.*?)">\r\n(.*?)\n.*?</a>'  #只匹配文章地址和名称
        reg = r'"link_title"><a href="(.*?)">\r\n        (.*?)            \r\n.*?</a>[\s\S]*?阅读</a>\((.*?)\)</span>'  # 匹配地址、名称、阅读数目
        getdata(html,reg)
        getlink(url,html)

    except urllib2.URLError, e:
        if hasattr(e,"code"):
            print e.code
        if hasattr(e,"reason"):
            print e.reason

for url in alllink:
    craw(url)
  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

腾讯AI架构师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值