简单的正文抽取方法

简单的正文抽取方法

import re
from bs4 import BeautifulSoup,Comment
import requests

authorset ={'责任编辑','作者'}

def filter_tags(html_str):
    soup =BeautifulSoup(html_str)
    title =soup.title.string.encode().decode('utf-8')
    # a = soup.findAll('script')[1]
    # print(a)
    #先把html里script,style给清理了
    [script.extract() for script in soup.findAll('script')]
    [style.extract() for style in soup.findAll('style')]

    # 把不属于HTML元素的垃圾数据清除掉
    comments = soup.findAll(text=lambda text: isinstance(text, Comment))
    [comment.extract() for comment in comments]

    # prettify()函数,把代码格式给搞的标准一些: soup.prettify()
    # reg1.sub()使用正则把所有的标签和 属性替换掉,只保留标签中的部的数据
    reg1 = re.compile("<[^>]*>")
    content = reg1.sub('', soup.prettify()).split('\n')

    return title,content

def getcontent(lst,title,authorset, ret_html=False):
    # 所有文本数据的的长度

    list = [l.strip() for l in lst if not l.strip() is ""]
    lstlen = [len(x) for x in list]
    threshold=30
    startindex = 0
    # 最大长度文本的索引
    maxindex = lstlen.index(max(lstlen))
    endindex = 0
    for i,v in enumerate(lstlen[:maxindex]):
        if v> threshold and lstlen[i+1]>10 and lstlen[i+2]>10 and lstlen[i+3]>10:
            startindex = i
            break
    for i,v in enumerate(lstlen[maxindex:]):
        if v< threshold and lstlen[maxindex+i+1]<10 :#and lstlen[maxindex+i+2]<10 #and lstlen[maxindex+i+3]<10:
            endindex = i
            break
    if ret_html:
        content =['<p>'+x.strip()+'</p>' for x in list[startindex:endindex+maxindex] if len(x.strip())>0]
    else:
        content = [x.strip()+"\n" for x in list[startindex:endindex + maxindex] if len(x.strip()) > 0]
    return content

def run(ctthtml):

    title,content =filter_tags(ctthtml)
    newcontent =getcontent(content,title,authorset)
    ctt =''.join(newcontent)
    return title,ctt
if __name__ == '__main__':
    
    url = "https://www.thepaper.cn/newsDetail_forward_2722515"
    # url = "http://news.ifeng.com/a/20181210/60188059_0.shtml?_zbs_baidu_news"
    headers = {}
    cookies = {}
    resp = requests.get(url=url ,headers=headers, cookies=cookies, timeout=6)
    html = resp.content.decode("utf8")
    if resp.status_code is 200:
        title,ctt = run(ctthtml=html)
        print(title)
        print(ctt)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_JackSparrow

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

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

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

打赏作者

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

抵扣说明:

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

余额充值