# _*_ coding:utf-8 _*_


"""
信息采集的流程
1.拼接获取列表连接
2.对详情页面内容进行解析和清洗
3.对采集的信息添加链接去重
4.文件内容的输出字段
5.内容信息调用请求的方式 requests,selenium

"""
import json

import redis
from bs4 import BeautifulSoup

import reqbase
import BaseCore
baseCore=BaseCore.BaseCore()
log=baseCore.getLogger()

rr=baseCore.r

def getList():

    header={
        'Accept':'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding':'gzip, deflate, br',
        'Accept-Language':'zh-CN,zh;q=0.9',
        'Cache-Control':'no-cache',
        'Content-Length':'185',
        'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
        'Origin':'https://sheng.so-gov.cn',
        'Pragma':'no-cache',
        'Referer':'https://sheng.so-gov.cn/',
        'Sec-Ch-Ua':'"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
        'Sec-Ch-Ua-Mobile':'?0',
        'Sec-Ch-Ua-Platform':'"Windows"',
        'Sec-Fetch-Dest':'empty',
        'Sec-Fetch-Mode':'cors',
        'Sec-Fetch-Site':'same-site',
        'Suid':'cf354a807a13d634f76bf167610f9c07',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'
    }
    dlist=[]
    pagenum=4
    for i in range(3,pagenum):
        log.info(f'henan采集第{i}页列表')
        lurl='https://api.so-gov.cn/s'
        data=f'siteCode=5300000033&tab=zcwj&timestamp=1699525503095&wordToken=72df37fd2f1058524e0c7467610d9ab7&page={i}&pageSize=20&qt=REITs&timeOption=0&sort=dateDesc&keyPlace=0&fileType=&toolsStatus=1'
        lcont=reqbase.reqPostHtml(lurl,header,data)
        if lcont:
            try:
                data=json.loads(lcont)
                datas=data['data']['search']['searchs']
                for myValues in datas:
                    lmsg=myValues['myValues']
                    try:
                        title=lmsg['DRETITLEO']
                        subtitle=''
                        summary=lmsg['QUICKDESCRIPTION']
                        createDate=''
                        writeDate=''
                        pubDate=''
                        source=lmsg['WEBSITENAME']
                        durl=lmsg['URL']
                        wenjianhao=lmsg['C3']
                        suoyinhao=''
                        content=''
                        siteweb='云南省人民政府'
                    except Exception as e:
                        continue
                    detailmsg={
                        'title':title,
                        'subtitle':subtitle,
                        'summary':summary,
                        'createDate':createDate,
                        'writeDate':writeDate,
                        'pubDate':pubDate,
                        'source':source,
                        'durl':durl,
                        'content':content,
                        'siteweb':siteweb,
                        'wenjianhao':wenjianhao,
                        'suoyinhao':suoyinhao,
                    }
                    is_member = rr.sismember('reis_yngov', durl)
                    if is_member:
                        continue
                    detailmsg=paserdetail(detailmsg)
                    dlist.append(detailmsg)
                    rr.sadd('reis_yngov',durl)

            except Exception as e:
                log.info(f'列表解析异常{e}')
    reqbase.pdwriterXLS(dlist,'云南人民政府-政策2')


def paserdetail(detailmsg):
    headers={
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Encoding':'gzip, deflate, br',
        'Accept-Language':'zh-CN,zh;q=0.9',
        'Cache-Control':'no-cache',
        'Connection':'keep-alive',
        'Cookie':'_gscu_802487706=99519044sn0ozi20; _gscbrs_802487706=1; Hm_lvt_b9099e95d08017e30f6285a8b55eb822=1699519045; TrsAccessMonitor=TrsAccessMonitor-1699519056000-2819180807; _gscs_802487706=995190442fewym20|pv:2; Hm_lpvt_b9099e95d08017e30f6285a8b55eb822=1699519714',
        'Host':'www.yn.gov.cn',
        'Pragma':'no-cache',
        'Referer':'https://sheng.so-gov.cn/',
        'Sec-Fetch-Dest':'document',
        'Sec-Fetch-Mode':'navigate',
        'Sec-Fetch-Site':'cross-site',
        'Sec-Fetch-User':'?1',
        'Upgrade-Insecure-Requests':'1',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
        'sec-ch-ua':'"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
        'sec-ch-ua-mobile':'?0',
        'sec-ch-ua-platform':'"Windows"',

    }
    durl=detailmsg['durl']
    dhmsg=reqbase.reqGetHtml(durl,headers)
    try:
        log.info(f'详情页标题：{detailmsg["title"]}')
        log.info(f'详情请求地址：{durl}')
        soup = BeautifulSoup(dhmsg, 'html.parser')
        soup = reqbase.paserUrl(str(soup), durl)
        suoyinhao=soupPaserHtml(soup,'div[class="referencebox"]>dl:nth-child(1)>dd')[1]
        wenjianhao=soupPaserHtml(soup,'div[class="referencebox"]>dl:nth-child(2)>dd')[1]
        pubDate=soupPaserHtml(soup,'div[class="referencebox"]>dl:nth-child(4)>dd')[1]
        contentWithTag,content=soupPaserHtml(soup,'div[class="trs_editor_view TRS_UEDITOR trs_paper_default trs_web"]')
        if not content:
            contentWithTag,content=soupPaserHtml(soup,'div[class="content"]')
        if not content:
            contentWithTag,content=soupPaserHtml(soup,'div[class="view TRS_UEDITOR trs_paper_default trs_external trs_web trs_key4format"]')
        if not content:
            log.info(f'详情内容为空：{durl}')
            #contentWithTag,content=soupPaserHtml(soup,'div[class="view TRS_UEDITOR trs_paper_default trs_external trs_web trs_key4format"]')

        detailmsg['contentWithTag']=contentWithTag
        detailmsg['content']=content
        detailmsg['suoyinhao']=suoyinhao
        detailmsg['wenjianhao']=wenjianhao
        detailmsg['pubDate']=pubDate

    except Exception as e:
        print(f'详情解析异常{e}')
    return detailmsg

def soupPaserHtml(soup,csstag):
    try:
        tagmsg=soup.select(csstag)[0]
        tagmsgtext=tagmsg.text
    except Exception as e:
        tagmsg=''
        tagmsgtext=''
        log.info(f'标签解析异常{e}')
    return  tagmsg,tagmsgtext

if __name__ == '__main__':
    getList()











