# _*_ coding:utf-8 _*_
# https://www.henan.gov.cn/
"""
信息采集的流程
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/plain, */*',
        'Accept-Encoding':'gzip, deflate',
        'Accept-Language':'zh-CN,zh;q=0.9',
        'Cache-Control':'no-cache',
        'Connection':'keep-alive',
        'Content-Length':'385',
        'Content-Type':'application/json',
        'Cookie':'Hm_lvt_a013af4793f2380a4bcf49ca1ce393eb=1699513646; _trs_uv=loqujlqp_3625_8md7; _trs_ua_s_1=loqujlqp_3625_2jhe; arialoadData=true; ariawapChangeViewPort=false; Hm_lpvt_a013af4793f2380a4bcf49ca1ce393eb=1699513657; SEARCHHISTORY=[%22REiTs%22]',
        'Host':'www.gxzf.gov.cn',
        'Origin':'http://www.gxzf.gov.cn',
        'Pragma':'no-cache',
        'Referer':'http://www.gxzf.gov.cn/irs-intelligent-search/search?code=181aedaa542&dataTypeId=241&configCode=&sign=9cc99c9d-94aa-44b4-aa79-41227a5385d7&orderBy=related&searchBy=all&appendixType=&granularity=ALL&isSearchForced=0&pageNo=1&pageSize=10&isAdvancedSearch&isDefaultAdvanced&advancedFilters%20&searchWord=REiTs&advancedFilters',
        '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=5
    for i in range(1,pagenum):
        log.info(f'采集第{i}页列表')
        lurl='http://www.gxzf.gov.cn/irs/front/search'
        data={
            "code": "181aedaa542",
            "dataTypeId": "241",
            "configCode": "",
            "sign": "9cc99c9d-94aa-44b4-aa79-41227a5385d7",
            "searchWord": "REiTs",
            "orderBy": "related",
            "searchBy": "all",
            "appendixType": "",
            "granularity": "ALL",
            "isSearchForced": "0",
            "filters": [],
            "pageNo": i,
            "pageSize": 10,
            "isAdvancedSearch": None,
            "isDefaultAdvanced": None,
            "advancedFilters": None,
            "advancedFilters ": None,
            "historySearchWords": [
                "REiTs"
            ]
        }
        lcont=reqbase.reqPostHtml(lurl,header,data)
        if lcont:
            try:
                data=json.loads(lcont)
                datas=data['data']['middle']['listAndBox']
                for lmsgg in datas:
                    lmsg=lmsgg['data']
                    title=lmsg['title']
                    subtitle=''
                    summary=lmsg['table-7']
                    createDate=''
                    writeDate=lmsg['table-4']
                    pubDate=lmsg['time']
                    source=lmsg['table-3']
                    durl=lmsg['url']
                    docNumberStr=lmsg['table-5']
                    reNum=lmsg['table-1']
                    content=''
                    siteweb='广西壮族自治区人民政府'
                    detailmsg={
                        'title':title,
                        'subtitle':subtitle,
                        'summary':summary,
                        'createDate':createDate,
                        'writeDate':writeDate,
                        'pubDate':pubDate,
                        'source':source,
                        'durl':durl,
                        'content':content,
                        'siteweb':siteweb,
                        'docNumberStr':docNumberStr,
                        'reNum':reNum,
                    }
                    is_member = rr.sismember('reis_gxgov', durl)
                    if is_member:
                        continue
                    detailmsg=paserdetail(detailmsg)
                    dlist.append(detailmsg)
                    rr.sadd('reis_gxgov',durl)

            except Exception as e:
                log.info(f'列表解析异常{e}')
    reqbase.pdwriterXLS(dlist,'广西壮族自治区人民政府')


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',
        'Accept-Language':'zh-CN,zh;q=0.9',
        'Cache-Control':'no-cache',
        'Connection':'keep-alive',
        'Cookie':'Hm_lvt_a013af4793f2380a4bcf49ca1ce393eb=1699513646; _trs_uv=loqujlqp_3625_8md7; _trs_ua_s_1=loqujlqp_3625_2jhe; arialoadData=true; ariawapChangeViewPort=false; SEARCHHISTORY=[%22REiTs%22]; Hm_lpvt_a013af4793f2380a4bcf49ca1ce393eb=1699514234',
        'Host':'www.gxzf.gov.cn',
        'Pragma':'no-cache',
        'Referer':'http://www.gxzf.gov.cn/irs-intelligent-search/search?code=181aedaa542&dataTypeId=241&configCode=&sign=9cc99c9d-94aa-44b4-aa79-41227a5385d7&orderBy=related&searchBy=all&appendixType=&granularity=ALL&isSearchForced=0&pageNo=1&pageSize=10&isAdvancedSearch&isDefaultAdvanced&advancedFilters%20&searchWord=REiTs&advancedFilters',
        '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'
    }
    durl=detailmsg['durl']
    dhmsg=reqbase.reqGetHtml(durl,headers)
    try:
        soup = BeautifulSoup(dhmsg, 'html.parser')
        soup = reqbase.paserUrl(str(soup), durl)
        #class_type=soupPaserHtml(soup,'div[class="people-desc"]>table>tbody>tr:nth-child(1)>td:nth-child(4)')[1]
        pub_jigou=soupPaserHtml(soup,'div[class="people-desc"]>table>tbody>tr:nth-child(2)>td:nth-child(1)')[1]
        write_data=soupPaserHtml(soup,'div[class="people-desc"]>table>tbody>tr:nth-child(2)>td:nth-child(2)')[1]
        #file_num=soupPaserHtml(soup,'div[class="classify"]>table>tbody>tr:nth-child(4)>td:nth-child(2)')[1]
        #pub_data=soupPaserHtml(soup,'div[class="classify"]>table>tbody>tr:nth-child(4)>td:nth-child(4)')[1]
        contentWithTag,content=soupPaserHtml(soup,'div[class="article-con"]')
        if not content:
            contentWithTag,content=soupPaserHtml(soup,'div[class="zw"]')
        detailmsg['contentWithTag']=contentWithTag
        detailmsg['content']=content
        # detailmsg['class_type']=class_type
        detailmsg['pub_jigou']=pub_jigou
        detailmsg['write_data']=write_data
    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()











