抓取新浪网的标题

刚想开始入手的时候,想着爬今日头条来的,但是看它那么难,就往后放了放,一直在跟前辈们沟通,但是中间也不能闲下来呀,所以,就穿插着又爬了一下新浪网的新闻,这个就比较简单了,直接查看网页源代码就可以找到他的信息,那接下来就直接上代码就可以了噻~

# coding=utf-8

import re
from bs4 import BeautifulSoup
import urllib2

class XL():
    def get_text(self):
        url = 'http://news.sina.com.cn/society/'
        try:
            req = urllib2.Request(url)
            response = urllib2.urlopen(req)
            webdata = response.read()
            re_script = re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>', re.I)  # 去掉一些冗余出来的数据
            webdata = re_script.sub("", webdata)
            webdata = re.sub('<div id="latestNewsNotification"[^>]*>[^<]*</div>', '', webdata)  # 去掉-有{n}条新闻更新,请点击查看
            webdata = re.sub('</a> <a target="(.*)</a>', '', webdata)  # 去掉-详细
            webdata = re.sub('<div><span class(.*)</a></span>', '', webdata)  # 去掉-Close
            webdata = re.sub('<span class=(.*)</a></span></div>', '', webdata)  # 去掉登录
            webdata = re.sub('<div class="action">(.*)</span></span></div>', '', webdata)  # 去掉-分享、评论
            webdata = re.sub('<div class="time">(.*)</div>', '\n', webdata)  # 去掉时间

            soup = BeautifulSoup(webdata, 'html.parser')
            tags = soup.find('div', class_="blk6-c")    #从此处一直到此类型包括的结束处
            return tags
        except Exception as error:
            print error

    def get_title(self):
        file = open('xinlang.txt', 'a')
        tag = self.get_text()
        m = 0
        for item in tag:
            if item not in ['\n', '\t', '']:
                m = m + 1
                item = str(m) + 'title' + item.get_text('\n', strip=True)
                file.write(item.encode('utf-8'))
                file.write('\n')
        file.close()

if __name__ == '__main__':
    XL().get_title()

以上就是我想要的信息的抓取代码,即下图所示的信息,其中有标题还有原来的原标题。


以上,谢谢大家,希望大家多多提出宝贵意见~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值