コード例 #1
0
 def checkEnd(self,url,flag):
     soup = makeBS().makesoup(url)
     m_page = soup.find("div",attrs={"class","m_page"})
     # print(m_page)
     nextFlag = False
     if m_page!=None:
         for a in m_page.find_all("a"):  #一个找全部闹出来那么久的东西
             # print(type(a))
             # print(a.text)
             if a.text.find("下一页")==0:
                 nextFlag=True
                 break
                 # return True #有就返回这个
     return nextFlag  #有下一页就继续遍历
コード例 #2
0
    def getOnePageUrl(self,url):  #找到有下一页按钮那就直接数字加起来就可以了,先点第一页的下一页
        soup  = makeBS().makesoup(url)  #统一使用了一样的
        dictt  =[]
        # button = soup.find("div",attrs={"class":"m_page"})
        if soup==None:
            return dictt
        li = soup.find_all("li")

        print(url)
        for i in li:
            if (i.h4!=None):
                title = i.a.text
                url = i.a['href']
                dictt.append(url)
                print(title,url)   #这儿只写入url和fromWhere就可以了
        print("找完一页的url")

        return dictt   #返回找到的url的列表在这里面给v你你
コード例 #3
0
    def getAwriteCommentJson(self,id,url):                                        #这个是评论专用的请求返回成字典的。
        time.sleep(1)
        cooker = makeBS()
        commentRawUrl = "http://coral.qq.com/article/"
        cmt_id = cooker.getCmt_id(url)  #去掉空格
        if cmt_id==None:
            return
        if cmt_id.find("'")!=-1:
            cmt_id = cmt_id.replace("'","")
        else :
            cmt_id = cmt_id.strip()

        # print(  cmt_id.strip()  )
        #这个用来拼接用到。
        try:
            allUrl = commentRawUrl + str(cmt_id) + "/comment/#"
            print(allUrl)
            responseDic = cooker.makeBSjson(allUrl)
            # if
            # print()
            print(responseDic)
            commentList = responseDic['data']['commentid']
            print(commentList)
            from pprint import pprint
            for comment in commentList:
                pprint(type(comment['id']))
                print(comment['id'])
                comment['content'] = emoji.demojize(comment['content'])      #过滤emoji
                comment['userinfo']['nick'] = emoji.demojize(comment['userinfo']['nick'])
                comment['time']=self.changTimeToDate(comment['time'])             #时间戳改成日期字符串
                print("新闻id "+ str(id))
                print("新闻的url是 "+ url)


                self.dbHelper.classifyDBComment(url=url,id=id,comment=comment)   #插入数据库。


                print("")
                #-----------------------这儿可以合成sql语句的话就可以执行插入的操作了。-----------------------
                # 通过url来合成插入的sql语句,DBcontrol的方法中来做这些东西
        except Exception as e:
            print("提取此条评论出错,正在跳过")
            print(e)
コード例 #4
0
    def getPlContent(self, url):  #打开pl.ifenghxxx的东西
        title, Hcontent, Tcontent, Acontent = "", "", "", ""
        t = time.time()
        timeStamp = str(int(round(t * 1000)))  # 毫秒级时间戳
        time.sleep(1)
        print("现在网页是:" + url)
        downloadTool = Download(r'/home/default/images')  # 设置下载路径
        dbhelper = DB()

        title, Hcontent, Tcontent, Acontent = "", "", "", ""
        simpleP = []
        soup = None
        soup = makeBS().makesoup(url)
        if soup != None:
            title = soup.find("head")
        else:
            return title, Hcontent, Tcontent, Acontent

        # print(title)
        # print("标题是")
        if title != None:  # 如果找到的话
            title = title.text.split("_")[0]
            # title=self.fixCssdot(title)
            # print(title)
        else:
            print("没能找到标题,请检查网址 " + url)
            # print(soup)
            # print()
            return title, Hcontent, Tcontent, Acontent  # 不行就返回空的回去

        flag = False  #遇到之前先不写入
        pList = []
        simplePList = []  #这个是
        for p in soup.find_all("p"):
            # print(type(p))
            # print(p)
            try:
                # print(p['class'])
                if p['class'][0] == "f14":
                    # print(p)
                    pList.append(p)
                    flag = True
                if p['class'][0] == "IphoneNone":
                    # print(p['class'])
                    flag = False  #结束跳出
            except Exception as e:
                if flag:
                    # print("正在添加")
                    pList.append(p)
                else:
                    # print("停止添加这一条")
                    break

        print(len(pList))  #这个最后一个句子是尾句,
        Plen = len(pList)

        if (len(pList) == 1):
            #一个句子的话,首段和尾端都统一起来好了
            print("这个文章只有一个句子 " + url)
            return title, pList[0], pList[0], pList[0]  #这样的话,就不插入

        for p in pList:
            # print(p)
            if p.text != "":
                pHtml = "<p>" + p.text + "</p>"
                if pList.index(p) == 0:  # 如果发现索引值是第一个的话,那就是开头了
                    Hcontent = pHtml
                    Acontent = Acontent + pHtml
                    # print("find the header p")
                    # print(phtml)
                elif pList.index(p) == len(pList) - 1:  # 同理如果是最后一个句子,那么你就是结尾了
                    Acontent = Acontent + pHtml
                    Tcontent = pHtml
                else:  # 不是首段和尾端的端口才加入到零散的段落中去
                    Acontent = Acontent + pHtml
                    simplePList.append(pHtml)
            else:  #可能是有图片的这个东西,如果有图片那就这百年这样操作
                if p.find("img") != None:
                    print("发现图片的段落")
                    for img in p.find_all("img"):  #修改图片路径和下载图片这两个操作
                        #修改里面的图片的地址的东西,然后还有别的什么的
                        imgSrc = img['src']
                        now = time.strftime('%Y%m%d',
                                            time.localtime(time.time()))
                        now_date = now + "/"  # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠

                        imgName = self.stripImgUrl(imgSrc)
                        print(imgName)

                        imgName = now_date + self.stripImgUrl(
                            imgName)  # 这儿已经是添加了时间的 了

                        # print("文件名是" + imgName)                                # 这儿下载这个图片到服务器指定的地址上 # 这儿下载这个图片到服务器指定的地址上
                        downloadTool.downloadImg(imgSrc,
                                                 imgName=imgName,
                                                 referer=None,
                                                 now_date=now)

                        imgPScr = "/images/" + imgName + ".jpg"  # 这个html格式图片地址
                        HtmlImg = '<p><img src="' + imgPScr + '"/></p>'

                        if pList.index(p) == 0:  # 如果发现索引值是第一个的话,那就是开头了
                            Hcontent = HtmlImg
                            Acontent = Acontent + HtmlImg

                        elif pList.index(
                                p) == len(pList) - 1:  # 同理如果是最后一个句子,那么你就是结尾了
                            Acontent = Acontent + HtmlImg

                            Tcontent = HtmlImg
                        else:  # 不是首段和尾端的端口才加入到零散的段落中去
                            Acontent = Acontent + HtmlImg

                            simplePList.append(HtmlImg)

        # print("开头结尾是这个")
        # print(Hcontent)
        # print(Tcontent)
        # print("各个分句子在这儿")
        for simpleP in simplePList:  #这儿直接写入进去就可以了
            dbhelper.insertSimpleP(simpleP)  # 这儿这个是一样的
            # print(simpleP)
        return title, Hcontent, Tcontent, Acontent
コード例 #5
0
    def getPageContent(self,
                       url):  #输入一个url获得这个页面的本地化后的文章   ,其实分这个应该是不需要那么麻烦的把,,,,
        t = time.time()
        timeStamp = str(int(round(t * 1000)))  # 毫秒级时间戳
        time.sleep(1)

        downhelp = Download(r'/home/default/images')  #设置下载路径
        dbhelper = DB()

        title, Hcontent, Tcontent, Acontent = "", "", "", ""
        simpleP = []
        soup = None
        try:
            soup = makeBS().makesoup(url)

            # print(soup)

            title = soup.find("head").title
            # print(chardet.detect(title.text))   测不准的这个东西
            # print(title)

            if title != None:
                title = title.text
                print("标题是" + str(title))
            main_content = soup.find("div", attrs={"id": "main_content"})
            flag = 1
            if (main_content != None):
                allPP = main_content.find_all("p")
                for p in range(0, len(allPP)):
                    # print()
                    # print(allPP[p])
                    # print(p)
                    if allPP[p].find_all("a") != None:
                        # print("找到了有链接的东西")
                        # print(allPP[p])
                        allPP[p].a.extract()
                        # print(allPP[p])

                    localImgList = allPP[p].find_all(
                        "img", attrs={"src": True})  # 每个p标签内的img提取和修改链接本地化

                    if (localImgList != None):  # 找到有的话就遍历,并且本地化还有修改src的东西
                        for img in localImgList:
                            if img != None:
                                # print("发现图片")
                                # print(img)
                                # print(img['src'])
                                if (img['src'].find("//") == 0
                                    ):  # 什么都没有,协议路径改成https
                                    imgSrc = "https:" + img['src']
                                    # print(imgSrc)

                                    now = time.strftime(
                                        '%Y%m%d', time.localtime(time.time()))
                                    now_date = now + "/"  # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠
                                    imgName = now_date + self.stripImgUrl(
                                        imgSrc)

                                    # print("文件名是" + imgName)

                                    # print(imgName)
                                    downhelp.downloadImg(
                                        imgSrc,
                                        imgName=imgName,
                                        referer=None,
                                        now_date=now)  # 下载这个是没问题的
                                    img['src'] = "/images/" + imgName + ".jpg"  #修改完后的img
                                    # print(img['src'])

                                    simpleP.append(allPP[p])
                                    Acontent += str(allPP[p])

                                    # Acontent += str(allcontent[i])
                                elif (img['src'].find("https:") == 0
                                      ):  # 本来就有找到有https协议
                                    imgSrc = img['src']
                                    # print(imgSrc)

                                    now = time.strftime(
                                        '%Y%m%d', time.localtime(time.time()))
                                    now_date = now + "/"  # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠
                                    imgName = now_date + self.stripImgUrl(
                                        imgSrc)

                                    downhelp.downloadImg(imgSrc,
                                                         imgName=imgName,
                                                         referer=None,
                                                         now_date=now)
                                    img['src'] = "/images/" + imgName + ".jpg"
                                    # print(img['src'])
                                    simpleP.append(allPP[p])
                                    Acontent += str(allPP[p])

                                else:  # 那这个就是http协议了
                                    imgSrc = img['src']
                                    # print(imgName)

                                    now = time.strftime(
                                        '%Y%m%d', time.localtime(time.time()))
                                    now_date = now + "/"  # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠
                                    imgName = now_date + self.stripImgUrl(
                                        imgSrc)

                                    downhelp.downloadImg(imgSrc,
                                                         imgName=imgName,
                                                         referer=None,
                                                         now_date=now)
                                    img['src'] = "/images/" + imgName + ".jpg"
                                    # print(img['src'])
                                    simpleP.append(allPP[p])
                                    Acontent += str(allPP[p])
                    if (p == 0):  #这儿是判断是首段还是尾段
                        Hcontent = allPP[p]  #这个是找标题的,这个是修改后的了
                    elif (p == len(allPP) - 1):
                        print("找到尾段了拉")
                        Tcontent = allPP[p]

                # for p in simpleP:
                # dbhelper.insertSimpleP(p) #这儿这个是一样的  todo 记得改回来这儿的地方
                return title, Hcontent, Tcontent, Acontent
            else:
                title = "凤凰没有找到标题"
                return title, Hcontent, Tcontent, Acontent
        except Exception as e:
            print(e)
            print("现在网页是:" + url)
            return title, Hcontent, Tcontent, Acontent
コード例 #6
0
    def getNewsContent(
            self,
            url):  # 打开news.ifenghxxx的东西,只要打开文章后,然后解析出 首段,尾段,还有中间的普通段落就可以了
        title, Hcontent, Tcontent, Acontent = "", "", "", ""
        t = time.time()
        timeStamp = str(int(round(t * 1000)))  # 毫秒级时间戳
        time.sleep(1)
        print("现在网页是:" + url)
        downloadTool = Download(r'/home/default/images')  # 设置下载路径
        dbhelper = DB()

        title, Hcontent, Tcontent, Acontent = "", "", "", ""
        simpleP = []

        soup = makeBS().makesoup(url)
        if soup == None:
            return title, Hcontent, Tcontent, Acontent

        try:
            title = soup.find("head").title
            if dbhelper.ifExists(title):  #如果找到已经存在那就不用再写的拉
                return title, Hcontent, Tcontent, Acontent  #存在的话,就不用再解析和下载图片了
        except Exception as e:
            #一般提示没找到都是
            return title, Hcontent, Tcontent, Acontent  #也当成没有处理掉就可以了

        # print(title)
        # print("标题是")
        if title != None:  # 如果找到的话
            title = title.text.split("_")[0]
            # title=self.fixCssdot(title)
            # print(title)
        else:
            print("没能找到标题,请检查网址 " + url)
            # print(soup)
            return title, Hcontent, Tcontent, Acontent  # 不行就返回空的回去

        flag = False  # 遇到之前先不写入
        pList = []
        simplePList = []  # 这个是

        for p in soup.find_all(
                "p"
        ):  #找到p就输出来就可以了        你好啊,大哥,我是你的第一个机械硬盘,感觉还行哈,灯光效果怎么样,不怎么会   # print(p.text)
            try:
                if p['class'][0] == "p_time":
                    flag = True
                    continue  #跳过这个的下面的,继续走
                if p['class'][0] == "detailPic":

                    #这儿找到后就下载图片,并且,修改src然后写入进去,就是那个模块了, todo 有空变成模块
                    imgSrc = p.img['src']
                    imgName = imgSrc.replace("https://inews.gtimg.com/",
                                             "").replace("/", "_")
                    now = time.strftime('%Y%m%d', time.localtime(time.time()))
                    now_date = now + "/"  # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠
                    imgName = now_date + self.stripImgUrl(
                        imgName)  # 这儿已经是添加了时间的 了

                    # print("文件名是" + imgName)                                # 这儿下载这个图片到服务器指定的地址上 # 这儿下载这个图片到服务器指定的地址上
                    downloadTool.downloadImg(imgSrc,
                                             imgName=imgName,
                                             referer=None,
                                             now_date=now)

                    # now_date = now + "/"                                     # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠
                    # imgName = now_date + self.stripImgUrl(imgName)   #已经处理好了
                    imgPScr = "/images/" + imgName + ".jpg"  # 这个html格式图片地址

                    #传进来是img的url下载并且修改后当成普通的段落进行处理
                    pList.append('<img src=' + imgPScr + '/>')  # 统一起来把,后面会有加东西
                    # print("<p><img src='"+p.img['src']+"'/></p>")
                if p.text == "用微信扫描二维码分享至好友和朋友圈":
                    flag = False  #找到了这个就是到结尾了
                    pass
            except Exception as e:
                pass
                if flag:
                    # print("正在添加")
                    pList.append(p)
                else:
                    # print("停止添加这一条")
                    break
        # print(len(pList))  # 这个最后一个句子是尾句,
        Plen = len(pList)
        if (len(pList) == 1):
            # 一个句子的话,首段和尾端都统一起来好了
            print("这个文章只有一个句子 " + url)
            return title, pList[0], pList[0], pList[0]  # 这样的话,就不插入

        PPlist = []
        continueFlag = False
        for pOne in pList:
            try:
                p = pOne.text
            except Exception:  #那就是图片的那个了,我知道是什么来的
                p = pOne
            # print(pOne)
            if (p != ""):
                # print(p.strip("\n"))
                if p.strip(
                        "\n"
                ) == "用微信扫描二维码分享至好友和朋友圈" and continueFlag == False:  #有些有有些没有的
                    # print("找到第一个这个东西")
                    # continue
                    continueFlag = True
                elif p.strip(
                        "\n"
                ) == "用微信扫描二维码分享至好友和朋友圈" and continueFlag == True:  #有些有有些没有的
                    # print("这儿是结束的地方")
                    continueFlag = "break"
                if continueFlag == True:
                    if (p != "用微信扫描二维码分享至好友和朋友圈"):
                        p = "<p>" + p + "</p>"
                        #这儿是把"'"  这个东西替换成'"'   这个东西
                        # if p.find("'")!=-1:
                        #     print("找到了这个东西")

                        PPlist.append(p)
                if continueFlag == 'break':
                    break

            else:
                pass  #图片都会在前面进行处理才对的
                #检查一下是不是图片的
                # print("文字卫空空那")
                # if pOne.find("img")!=None:  #因为图片是处理过的了,那么就直接加入进去就可以了
                #     print(p)

        # print(PPlist)

        if (len(PPlist)) == 1 and len(PPlist) == 2:  #还有2都是这种情况
            Hcontent = PPlist[0]
            Tcontent = PPlist[0]
            Acontent = PPlist[0]
        if (len(PPlist)) > 2:
            Hcontent = PPlist[0]
            Tcontent = PPlist[-1]
            for i in PPlist:
                Acontent = Acontent + i
                # print(i)  # 你好啊
            # Acontent = PPlist

        # print("普通的段落有")
        simplePList = PPlist[1:-1]

        # print(p)
        # print("开头结尾是这个")
        # print(Hcontent)
        # print(Tcontent)
        # print("各个分句子在这儿")
        for simpleP in simplePList:  # 这儿直接写入进去就可以了
            dbhelper.insertSimpleP(simpleP)  # 这儿这个是一样的
            # print(simpleP)
        return title, Hcontent, Tcontent, Acontent
コード例 #7
0
ファイル: pageUrls.py プロジェクト: realzhengyiming/LocalNews
    def tengxunGundong(self):
        url = 'http://news.qq.com/articleList/rolls/'
        cooker = makeBS()
        soup = cooker.makesoup(url, "computer")

        print(soup)
コード例 #8
0
    def getWxContent(self,wxUrl):#  先提取出里面的那个,然后再看看什么情况  ----这个是主要解析的函数
        time.sleep(1)

        title, Hcontent, Tcontent, Acontent = "", "", "", ""  # 最后一个参数好像没什么用
        downloadTool = Download(r'/home/default/images')  # 设置下载路径
        simplePList = []

        Cooker = makeBS()
        BS = Cooker.makesoup(wxUrl) #传进来是微信的才可以一
        # print(BS)
        if BS==None:
            return title, Hcontent, Tcontent, Acontent
        # print(BS)
        try:
            title = BS.find("head").title    #直接选用head这儿的title标签里面的东西
        except Exception as e:
            print(e)
            traceback.print_exc()  # 貌似这个,一个错,各个错。
            return title, Hcontent, Tcontent, Acontent

        # print("输出title")

        #todo 这儿插入一个检查一下标题是否存在的东西的

        # print(title.text)                 #todo 改变成手机的ua,让服务器发来手机端页面来给我, 我怀疑现在ua打开的还是电脑版本的
        if(title!=None and title.text!="404 - 腾讯网"):
            title=title.text
            if self.dbhelper.ifExists(title):  #如果标题为空那就直接删除这条了。 ,所以就是因为已经存在,所以后面都不进行读取了对吧
                print("已经存在了这个")
               #这儿也是返回空值的。
                return title,Hcontent,Tcontent,Acontent  #存在的话,就不用再解析和下载图片了  ,如果只有标题没有别的,很可能是这个新闻标题已经存在
        else:
            print("此新闻可能已经被删除,提取失败")
            return title,Hcontent,Tcontent,Acontent

        dicString = ""
        '''
        测试区域
        '''
        print(BS)

        for script in BS.find_all("script", attrs={"async": False}):  # 这边应该找内容不为空的
            if script.text!=None and script.text!="":
                print(script.text)
                dicString = script.text
                break



        # dicString = BS.find("script", attrs={"async": False}).text  #这边应该找内容不为空的
        # print(dicString)
        print(dicString)
        dic = dicString.replace("var globalConfig =", "").replace(";", "")
        # print(dic)
        tempDic = dic
        print("解析的文章的部分-》")  # 这边已经是空的了//todo 把腾讯的这个分析的东西再搞一下,应该还是解析页面里面除到问题就是这个文件里面的。
        print(tempDic)
        if dic.find("contents: ") != -1:

            datalist = dic.split("contents: ")[1].split("ext_data")[0].replace("[", "").replace("],", "")
            # print("这边开始这样")
            #这个是新加的。
            print(datalist)

            try:
                dic = eval("(" + datalist + ")")  #因为加了这个才能转化成那样,这个应该也是没问题才对。
                # print(dic)
            except Exception as e:
                print("转化成json出错")
                print(e)
                traceback.print_exc()  # 貌似这个,一个错,各个错。
                return title,Hcontent,Tcontent,Acontent  #存在的话,就不用再解析和下载图片了

                #return #返回空内容给他们咯,自动舍弃这个东西,然后那边要处理了一下,空内容的情况,这个不对啊。
            checkLen = len(dic)
            pprint.pprint(dic)
            print(checkLen)  #这儿需要考虑只有一个句子的情况,这个情况下是长度为2,这个情况下不是列表了,只是一个字典
            if(checkLen>2):
                for p in dic:   #遍历每一个,然后尽心判断应该也是没问题才对的。
                    try:  #traceback.print_exc()
                        if p['type'] == 1:  # 这个是一个句子,那就直接插进去就可以了
                            # 当成句子插入

                            pContent = p['value']
                            phtml='<p>'+pContent+"</p>"

                            Acontent =Acontent+phtml

                            if dic.index(p)==0:                      #如果发现索引值是第一个的话,那就是开头了
                                Hcontent= phtml
                                # print("find the header p")
                                # print(phtml)
                            elif dic.index(p)==checkLen-1 :            #同理如果是最后一个句子,那么你就是结尾了
                                Tcontent = phtml
                            else:  # 不是首段和尾端的端口才加入到零散的段落中去
                                simplePList.append(phtml)



                        # print(phtml)
                        if p['type'] == 2:
                            imgSrc = p['value'].replace("\/", "/")                    #图片的真实下载地址
                            # print(imgSrc)
                            imgName = imgSrc.replace("https://inews.gtimg.com/", "").replace("/", "_")
                            now = time.strftime('%Y%m%d', time.localtime(time.time()))
                            now_date = now + "/"  # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠
                            imgName = now_date + self.stripImgUrl(imgName)   #这儿已经是添加了时间的 了

                            # print("文件名是" + imgName)                                # 这儿下载这个图片到服务器指定的地址上 # 这儿下载这个图片到服务器指定的地址上
                            downloadTool.downloadImg(imgSrc, imgName=imgName, referer=None, now_date=now)

                            # now_date = now + "/"                                     # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠
                            # imgName = now_date + self.stripImgUrl(imgName)   #已经处理好了
                            imgPScr = "/images/" + imgName + ".jpg"                 # 这个html格式图片地址
                            HtmlImg = '<p><img src="'+imgPScr+'"/></p>'

                            # print(imgPScr)

                            Acontent = Acontent + HtmlImg
                            # print("这个是图片了 "+HtmlImg)

                            if dic.index(p)==0:                      #如果发现索引值是第一个的话,那就是开头了
                                # print("find the header p")
                                # print(HtmlImg)
                                Hcontent= HtmlImg
                            elif dic.index(p)==checkLen-1 :            #如果是最后一个句子,那么你就是结尾了
                                Tcontent = HtmlImg
                            else:  # 不是首段和尾端的端口才加入到零散的段落中去
                                simplePList.append(HtmlImg)

                        if p['type'] == 3:  # 这个是视频的情况,直接提取出来当成句子好了,这儿还有图片的,先不管了
                            try:
                                pContent = p['value']['desc']
                                pContent = "<p>"+ pContent+"</p>"
                                # 解析视频
                                vid = self.findVideo(tempDic)
                                rawVideoString = ""
                                if vid != None:
                                    rawVideoString = '<p><iframe frameborder="0" src="https://v.qq.com/txp/iframe/player.html?vid=' + vid + '" allowFullScreen="true"></iframe></p>'

                                if dic.index(p) == 0:  # 如果发现索引值是第一个的话,那就是开头了
                                    # print("find the header p")
                                    # print(pContent)
                                    Hcontent = pContent+rawVideoString
                                elif dic.index(p) == checkLen - 1:  # 如果是最后一个句子,那么你就是结尾了
                                    Tcontent =pContent+rawVideoString
                                else:                              #不是首段和尾端的端口才加入到零散的段落中去
                                    simplePList.append(pContent)

                            except Exception as e:
                                pass  #舍弃这个段落
                    except Exception as e:
                        print(e)
                        traceback.print_exc()   #貌似这个,一个错,各个错。
                #插入数据库先
                # for p in simplePList:
                #     self.dbhelper.insertSimpleP(p)  #插入段落,但是没有更新标题还有那些东西

                Tcontent = "".join(BeautifulSoup(Acontent, 'lxml').text)
                return title, Hcontent, Tcontent, Acontent

            else :                                                         #这儿是只有一个句子的网页的情况下  ,这边的一个大段落的,首段尾段的拆分是没问题的
                p= dic                                                    #这样转换一下就可以了
                # print(type(dic))
                # print(dic)
                # print(p)
                if type(p)==tuple:
                    print("是tuple")
                    try:
                        # print("长度是")
                        # print(len(p))
                        if(len(p)==1):         #又加了一种,怕不够长的处理
                            p=p[0] # 如果是里面只有一个的话,那就提取出里面的一个元素就可以了,
                        if(len(p)==2):
                            p=p[1] # 如果是里面只有一个的话,那就提取出里面的一个元素就可以了,
                        else:                           #长度为空,里面除了标题,连文字内容都没有的这种。。。
                            p={'type':3}                     #开头结尾都是自己了,标题就也当成是这个来处理了

                    except Exception as e:
                        print(e)           #https://xw.qq.com/a/house/20180928003713  对付这个网页的情况
                        title,Hcontent,Tcontent,Acontent="","","",""   #这样就可以拉
                        return  title, Hcontent, Tcontent, Acontent#直接不要这个url的内容了

                # print(p)
                if p['type'] == 1:                                       # 这个是一个句子,那就直接插进去就可以了
                    # 当成句子插入
                    pContent = p['value']                                   #提取出句子来作为首段尾端还有   中间的段落
                    # print("长度有")
                    # print(pContent.split("。"))
                    # print(len(pContent.split("。")))
                    try:
                        Tcontent = "<p>"+pContent.split("。")[-2] +"</p>"           #最后一句作为 结尾的句子,句号前面那个才是
                    except Exception as e:
                        Tcontent="<p>"+pContent.split("。")[0] +"</p>"   #无法分的话,比如一句话,那就头尾都一样把
                    Hcontent = "<p>"+pContent.split("。")[0] +"</p>"            #这儿是开头的第一句的句子  ,
                    simplePList.append(pContent)                                 #整个把,没办法了饿

                    phtml = '<p>' + pContent + "</p>"
                    Acontent = Acontent + phtml
                    # print(phtml)

                if p['type'] == 2:
                    imgSrc = p['value'].replace("\/", "/")  # 图片的真实下载地址
                    # print(imgSrc)
                    imgName = imgSrc.replace("https://inews.gtimg.com/", "").replace("/", "_")
                    now = time.strftime('%Y%m%d', time.localtime(time.time()))
                    now_date = now + "/"  # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠
                    imgName = now_date + self.stripImgUrl(imgName)

                    # print("文件名是" + imgName)  # 这儿下载这个图片到服务器指定的地址上 # 这儿下载这个图片到服务器指定的地址上
                    downloadTool.downloadImg(imgSrc, imgName=imgName, referer=None, now_date=now)


                    # now_date = now + "/"  # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠
                    # imgName = now_date + self.stripImgUrl(imgName)
                    imgPScr = "/images/" + imgName + ".jpg"  # 这个html格式图片地址

                    # print(imgPScr)
                    HtmlImg = '<p><img src="' + imgPScr + '"/></p>'
                    Acontent = Acontent + HtmlImg
                    # print("这个是图片了 " + HtmlImg)

                if p['type'] == 3  :                  #只有一个视频的时候,解析视频
                    pContent = title
                    # print(pContent)

                    #解析视频
                    vid = self.findVideo(tempDic)
                    rawVideoString =""
                    if vid!=None:
                        rawVideoString='<p><iframe frameborder="0" src="https://v.qq.com/txp/iframe/player.html?vid='+vid+'" allowFullScreen="true"></iframe></p>'


                    #只有一个句子的东西是没有这个索引值的
                    # if dic.index(p) == 0:  # 这种情况就是只有一个视频的网页,标题就是唯一的开头了,那结尾呢,已经不能分了把,视频又没找到
                    #     print("find the header p")
                    #     print(pContent)
                    Hcontent = pContent                  #头是描述
                    Tcontent = rawVideoString            #尾是视频作为一个独立的一个段落
                #插入数据库先
                for p in simplePList:
                    self.dbhelper.insertSimpleP(p)  #插入段落,但是没有更新标题还有那些东西
                Tcontent = "".join(BeautifulSoup(Acontent, 'lxml').text)
                return title, Hcontent, Tcontent, Acontent                  #返回了后就可以写入数据库了把
コード例 #9
0
 def getWxContentNew(self,url):
     wxUrl = self.changeNewToWx(url)
     Cooker = makeBS()
     title, Hcontent, Tcontent, Acontent = "", "", "", ""  # 最后一个参数好像没什么用
     downloadTool = Download(r'/home/default/images')  # 设置下载路径
     BS = Cooker.makesoup(wxUrl) #传进来是微信的才可以一
コード例 #10
0
import time
import traceback

from DBcontrol import DB
from downloadPic import Download  #这些就是导入的类啊
from makebeautifulSoup import makeBS
from bs4 import BeautifulSoup
from pprint import pprint

Cooker = makeBS()

commentRawUrl = "http://coral.qq.com/"  # id附在上面就可以读取出来的了。
cmt_id = 2326922651
# response = requests.get(commentRawUrl+str(cmt_id))
BS = Cooker.makesoup(commentRawUrl + str(cmt_id))  # 传进来是微信的才可以一

pprint(BS)
"http://coral.qq.com/article/2326922651/comment/#"  #把id塞到这个链接可以返回50条评论。json格式。
コード例 #11
0
    def getNewsContent(self, url):  #解析图片类的,可以都放到类构造函数中去的
        title, Hcontent, Tcontent, Acontent = "", "", "", ""  #初始化一下
        allP = []  # 这个是装所有的段落
        simplePList = []  # 中间的段落
        downloadTool = Download(r'/home/default/images')  # 设置下载路径
        cooker = makeBS()
        soup = cooker.makesoup(url)  #soup 可能已经是空的了
        if soup == None:
            print("出现空的url ", url)
            return title, Hcontent, Tcontent, Acontent
        try:
            title = soup.find("head")  # 这个其实是head,是头部。
            # print(title)
            # time.sleep(60)
        except Exception as e:
            print(e)
            traceback.print_exc()  #这句用来告诉自己这儿需要跳出

            # print(title)
        # print("标题是")
        if title != None:  # 如果找到的话
            title = title.text.split("_")[0]
            print(title)
            # time.sleep(60)
            # title=self.fixCssdot(title)
            if self.dbhelper.ifExists(title):
                return title, Hcontent, Tcontent, Acontent  #存在的话,就不用再解析和下载图片了
            # print(title)
        else:
            print("没能找到标题,请检查网址 " + url)
            # print(soup)
            # print()
            return title, Hcontent, Tcontent, Acontent  # 不行就返回空的回去

        if url.find(
                "photoview") != -1:  #===============================解析图片滚动的页面的
            print("是图片集合的页面")
            # print(soup)
            for span in soup.find_all("img", attrs={"src": True}):
                print(span)
            return  #返回空白的回去,不要这个图

        else:  #--===================================================普通的文本图文的新闻
            pass  #这种是常规的新闻页面的解析
            # print(soup)

            pList = soup.find_all("p")
            checkLen = len(pList)

            for p in pList:  #解析常规的这几个东西
                # print(p)
                if p.img != None:
                    # print("图片段落")
                    # print(p)
                    try:
                        imgSrc = p.img['src']
                        imgName = imgSrc.replace("https://inews.gtimg.com/",
                                                 "").replace("/", "_")
                        now = time.strftime('%Y%m%d',
                                            time.localtime(time.time()))
                        now_date = now + "/"  # 后面下载的文件名是不需要带杠的,后面就不需要带杠杠
                        imgName = now_date + self.stripImgUrl(
                            imgName)  # 这儿已经是添加了时间的 了

                        # print("文件名是" + imgName)                                # 这儿下载这个图片到服务器指定的地址上 # 这儿下载这个图片到服务器指定的地址上
                        downloadTool.downloadImg(imgSrc,
                                                 imgName=imgName,
                                                 referer=None,
                                                 now_date=now)

                        imgPScr = "/images/" + imgName + ".jpg"  # 这个html格式图片地址
                        HtmlImg = '<p><img src="' + imgPScr + '"/></p>'
                        # print(HtmlImg)                                          #这个是修好的图片的文本的
                        allP.append(HtmlImg)  #放入列表中去

                    except Exception as e:
                        print(e)
                        print("找不到图片的地址")
                        print(p)
                        print()

                else:  #这就是普通的段落
                    if p.text != "用微信扫码二维码" and p.text != "分享至好友和朋友圈" and p.text != "" and p.text != "\n":
                        # print("普通段落")
                        if p.a == None:  #这儿开始判断是不是第一段
                            # print(p)
                            allP.append('<p>' + p.text +
                                        '</p>')  #只要文字进来,不要样式之类的

        # 最后再来判断首尾,这个也行的哈,对吧
        for p in allP:
            if (len(allP)) >= 2:
                Acontent = Acontent + str(p)
                if allP.index(p) == 0:  # 如果发现索引值是第一个的话,那就是开头了
                    Hcontent = p
                elif allP.index(p) == len(allP) - 1:  # 如果是最后一个句子,那么你就是结尾了
                    Tcontent = p
                else:  # 不是首段和尾端的端口才加入到零散的段落中去
                    simplePList.append(p)  #这儿存各种各样的列表

            else:  #如果这个也是一整段的新闻的话
                Acontent = Acontent + str(p)
                try:
                    Tcontent = "<p>" + p.split(
                        "。")[-2] + "</p>"  # 最后一句作为 结尾的句子,句号前面那个才是
                except Exception as e:
                    Tcontent = "<p>" + p.split(
                        "。")[0] + "</p>"  # 无法分的话,比如一句话,那就头尾都一样把
                Hcontent = "<p>" + p.split("。")[0] + "</p>"  # 这儿是开头的第一句的句子  ,
                simplePList.append(p)
        # print("title")
        # print(title)
        # print("Hcontent")
        # print(Hcontent)
        # print("Tcontent")
        # print(Tcontent)
        # print("Acontent")
        # print(Acontent)
        return self.fixCssdot(title), self.fixCssdot(Hcontent), self.fixCssdot(
            Tcontent), self.fixCssdot(Acontent)  #最后进行返回这些东西进来这儿