孤荷凌寒自学python第七十五天开始写Python的第一个爬虫5

孤荷凌寒自学python第七十五天开始写Python的第一个爬虫5

(完整学习过程屏幕记录视频地址在文末)

今天在上一天的基础上继续完成对我的第一个代码程序的书写。

直接上代码。详细过程见文末屏幕录像。

```

import requests

from bs4 import BeautifulSoup

import re

import datetime

import pymongo

import _mty

import _mf

import _mbs4

import _mmongo

import _mre

import _mdb

import _mword

intc=0

def msgbox(info,titletext='孤荷凌寒的DB模块对话框QQ578652607',style=0,isShowErrMsg=False):

    return _mty.msgboxGhlh(info,titletext,style,isShowErrMsg)

def myfirst(s,h):

    c2=_mdb.conLocaldbGhlh(r'C:ProgramDataSQLITE3slone.s3db')

    lstNm=['id','title','newdate','source','content','adddate']

    lstType=['int','string','date','str','memo','date']

    lstLong=[0,255,0,255,0,0]

    lstNull=['not null','not null','not null','null','not null','null']

    lstPrimary=[True,False,False,False,False,False]

    lstAuto=[True,False,False,False,False,False]

    c3=_mdb.conLocaldbGhlh(r'C:ProgramDataSQLITE3 ew163.accdb')

    strt='news163'

    a=_mdb.newTablePlusGhlh('sqlite',c2,strt,lstNm,lstType,lstLong,lstNull,lstPrimary,lstAuto)

    msgbox(str(a))

    cursor=c2.cursor()

    b=_mdb.newTablePlusGhlh('acc',c3,strt,lstNm,lstType,lstLong,lstNull,lstPrimary,lstAuto)

    cursor3=c3.cursor()

    cursor.execute('select * from ' + strt + ';')

    data=cursor.fetchall()

    for i in data:

        msgbox(str(i))

    cursor3.execute('select * from ' + strt + ';')

    data=cursor3.fetchall()

    for i in data:

        msgbox(str(i))

    #return True

    #-------------------------

    r=requests.get(s,headers=h)

    #print(r.text) #r.text得到的是页面源html代码

    _mf.writeAllTextToTxtFileGhlh('1.txt',r.text)

    bs=BeautifulSoup(r.text,features="lxml") #第二个参数指明了解析器,得到的是一个beautifulsoup对象

    s=bs.prettify()

    _mf.writeAllTextToTxtFileGhlh('2.txt',str(s))

    rs=bs.select('.bigsize') #选择指定style样式表的html标签元素

    for i in rs:

        ele=i.find_all('a') #每个h5标签下只有一个a标签

        strls=ele[0].get('href')

        #msgbox(strls) #取出地址

        getcontentpage(strls,h,c2,cursor,c3,cursor3,strt)

        #break

    #---------------------

    #cursor.execute('select * from ' + strt + ';')

    #data=cursor.fetchall()

    #for i in data:

    #    msgbox(str(i))

    #cursor3.execute('select * from ' + strt + ';')

    #data=cursor3.fetchall()

    #for i in data:

    #    msgbox(str(i))

   

def getcontentpage(strurl,h,c2,cursor,c3,cursor3,strt):

    r=requests.get(strurl,headers=h)

    _mf.writeAllTextToTxtFileGhlh('3.txt',r.text)

    bs=BeautifulSoup(r.text,features="lxml") #第二个参数指明了解析器,得到的是一个beautifulsoup对象

    s=bs.prettify()

    _mf.writeAllTextToTxtFileGhlh('4.txt',str(s))

    #---------------------------

    #eletemp=bs.find_all("#epContentLeft") #现在eletemp是一个rs集合对象

    #上一句是错误的,通过html标签对象的id值来查找应当使用的方法是:select方法

    eletemp=bs.select('#epContentLeft') #list

    #msgbox(str(type(eletemp)))

    eletitleparent=eletemp[0] #bs.element.Tag

    #msgbox(str(type(eletitleparent)))

    eletitle=eletitleparent.h1

    elesource=eletitleparent.div #elesource这种对象现在被称为:bs.element.Tag对象,可以被转换为列表,但不是列表

    #msgbox(str(elesource))

    strtitle=_mbs4.getAllTextGhlh(eletitle)

    strdate=list(elesource)[0]

    strdate=_mre.getDateAndTimeString(strdate)

    strsource=_mbs4.getAllTextGhlh(elesource.a)

    #msgbox(strtitle)

    #msgbox(strsource)

    #msgbox(strdate)

    #取正文

    elecontent=bs.select('#endText') #所有的正文内容都这个div中,elecotent是一个List?

    strcontent=_mbs4.getAllTextGhlh(elecontent)

    data={

        u'标题':strtitle,

        u'日期':strdate,

        u'来源':strsource,

        u'内容':strcontent,

        u'添加日期':datetime.datetime.now().__format__('%Y-%m-%d %H:%M:%S')

    }

    #msgbox(str(data))

    #写入Mongodb数据库

    c=_mmongo.conMongoDbGhlh('localhost')

    db=c.news163

    jh=db.first

    isok=_mmongo.addNewDataGhlh(jh,data)

    #msgbox(isok)

    #写入sqlite3和ACCESS数据库

    try:

        strsql="insert into " + strt + "(title,newdate,source,content,adddate) values('" + strtitle + "','" + strdate + "','" + strsource + "','" + strcontent + "','" + datetime.datetime.now().__format__('%Y-%m-%d %H:%M:%S') + "');"

        cursor.execute(strsql)

        cursor3.execute(strsql)

        c2.commit()

        c3.commit()

    except:

        msgbox('出错了')

    #写入word文档

    try:

        global intc

        intc=intc+1

        strf='%03d' %intc

        strf=strf + '.docx'

        strf='I:\MAKEAPP\python\Python365\边学习边测试文件夹\自学PYTHON部分\0075第七十五天爬虫实战5\' + strf

        f=_mword.newDocX(strf)

        f.add_heading(strtitle,level=2)

        f.add_heading(strsource,level=3)

        _mword.addPToDocx(f,strcontent)

        f.save(strf) #保存时必须有文件名作参数

        #f.close() #没有这个命令

    except:

        msgbox('写word出错!')

        pass

strurl='http://tech.163.com/special/techscience/'

header={

'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',

'Accept-Encoding':'gzip, deflate',

'Accept-Language':'zh-CN,zh;q=0.9',

'Cache-Control':'max-age=0',

'Connection':'keep-alive',

'Cookie':'_ntes_nuid=4c64ad6c80e3504f05302ac133efb277; _ntes_nnid=eb7c24e0daf48e922e31dc81e431fde2,1536978956105; Province=023; City=023; NNSSPID=acab5be191004a2b81a3a6ee60f516dc; NTES_hp_textlink1=old; UM_distinctid=1683adcaeaf2f8-0e31bcdad8532c-3c604504-144000-1683adcaeb094d; vjuids=-7a5afdb26.1683adccded.0.d9d34439a4e48; vjlast=1547175776.1547175776.30; ne_analysis_trace_id=1547175775731; s_n_f_l_n3=7476c45eb02177f91547175775852; vinfo_n_f_l_n3=7476c45eb02177f9.1.0.1547175775852.0.1547176062972',

'Host':'tech.163.com',

'If-Modified-Since':'Fri, 11 Jan 2019 03:01:05 GMT',

'Referer':'http://tech.163.com/',

'Upgrade-Insecure-Requests':'1',

'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'

}

header2={

    'Host':'tech.163.com',

    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'

}

myfirst(strurl,header2)

```

二、今天为了将爬到的新闻放到word文档中,写了辅助的word模块自定义的函数模块

【_mword.py】

```

#!/usr/bin/env python3

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

import string

from docx import *

from docx.shared import Inches

import _mty

import _cl #常用常量模块

import _mre

mwordErrString=''

def msgbox(info,titletext='孤荷凌寒的word模块对话框QQ578652607',style=0,isShowErrMsg=False):

    return _mty.msgboxGhlh(info,titletext,style,isShowErrMsg)

def newDocX(strfilenm,isShowMsg=False):

    '''

    创建一个新的docx并保存在指定的路径下成为指定文件名的文件 。

    '''

    try:

        f=Document() #创建新文档 对象

        f.save(strfilenm) #保存这个文件

        return f #f的类型是:<class 'docx.document.Document'>

    except Exception as e:

        mwordErrString='尝试创建一个新的word文件时出错:' + str(e) + ' 此函数由【孤荷凌寒】创建,QQ578652607'

        if isShowMsg==True:

           msgbox(mwordErrString)

        return None

    else:

        pass

    finally:

        pass

def addPToDocx(f,strp,isShowMsg=False):

    try:

        lst=strp.split(' ')

        for i in lst:

            i.strip()

            p=f.add_paragraph(i)

            #---接下来可调整格式

        return True

    except Exception as e:

        mwordErrString='尝试将来自网页的内容写入word文档正文时出错:' + str(e) + ' 此函数由【孤荷凌寒】创建,QQ578652607'

        if isShowMsg==True:

           msgbox(mwordErrString)

        return False

    else:

        pass

    finally:

        pass

#f=newDocX(r'I:MAKEAPPpythonPython365边学习边测试文件夹自学PYTHON部分075第七十五天爬虫实战5孤荷凌寒.docx')

#print(type(f))

```

三、安装word模块与了解到的一些知识

(一)、安装Python-docx

在windows的命令行窗口中输入:

pip install python-docx

(二)、官方文档的引用此模块的声明书写:

from docx import *

from docx.shared import Inches

官方文档:

https://python-docx.readthedocs.io/en/latest/index.html

今天只进行了初略了解,对此模块对象还没有深入研究。

四、其它感受

今天已成功解决了昨天没有解决的写入sqlite数据库的问题,而且今天发现,

关系型数据库的

insert

sql语句应当是可以通用的,那么完成一个统一的通用添加函数,最好与nosql数据库都统一起来就更好,这样对数据存取入数据库的代码书写和记忆来说都要简化很多。

——————————

今天整理的学习笔记完成,最后例行说明下我的自学思路:

根据过去多年我自学各种编程语言的经历,认为只有真正体验式,解决实际问题式的学习才会有真正的效果,即让学习实际发生。在2004年的时候我开始在一个乡村小学自学电脑 并学习vb6编程语言,没有学习同伴,也没有高师在上,甚至电脑都是孤岛(乡村那时还没有网络),有的只是一本旧书,在痛苦的自学摸索中,我找到适应自己零基础的学习方法:首先是每读书的一小节就作相应的手写笔记,第二步就是上机测试每一个笔记内容是否实现,其中会发现书中讲的其实有出入或错误,第三步就是在上机测试之后,将笔记改为电子版,形成最终的修订好的正确无误的学习笔记 。

通过反复尝试错误,在那个没有分享与交流的黑暗时期我摸黑学会了VB6,尔后接触了其它语言,也曾听过付费视频课程,结果发现也许自己学历果然太低,就算是零基础的入门课程,其实也难以跟上进度,讲师的教学多数出现对初学者的实际情况并不了解的情况,况且学习者的个体也存在差异呢?当然更可怕的是收费课程的价格往往是自己难以承受的。

于是我的所有编程学习都改为了自学,继续自己的三步学习笔记法的学习之路。

当然自学的最大问题是会走那么多的弯路,没有导师直接输入式的教学来得直接,好在网络给我们带来无限搜索的机会,大家在网络上的学习日志带给我们共享交流的机会,而QQ群等交流平台、网络社区的成立,我们可以一起自学,互相批评交流,也可以获得更有效,更自主的自学成果。

于是我以人生已过半的年龄,决定继续我的编程自学之路,开始学习python,只希望与大家共同交流,一个人的独行是可怕的,只有一群人的共同前进才是有希望的。

诚挚期待您的交流分享批评指点!欢迎联系我加入从零开始的自学联盟。

这个时代互联网成为了一种基础设施的存在,于是本来在孤独学习之路上的我们变得不再孤独,因为网络就是一个新的客厅,我们时刻都可以进行沙龙活动。

非常乐意能与大家一起交流自己自学心得和发现,更希望大家能够对我学习过程中的错误给予指点——是的,这样我就能有许多免费的高师了——这也是分享时代,社区时代带来的好福利,我相信大家会的,是吧!

根据完全共享的精神,开源互助的理念,我的个人自学录制过程是全部按4K高清视频录制的,从手写笔记到验证手写笔记的上机操作过程全程录制,但因为4K高清文件太大均超过5G以上,所以无法上传至网络,如有需要可联系我QQ578652607对传,乐意分享。上传分享到百度网盘的只是压缩后的720P的视频。

我的学习过程录像百度盘地址分享如下:(清晰度:1280x720)

链接:https://pan.baidu.com/s/1zjlWH2maPabigrLeDnSnbg

提取码:2adh

Bilibili:

https://www.bilibili.com/video/av40813661/

喜马拉雅语音笔记:

https://www.ximalaya.com/keji/19103006/154269324

欢迎大家添加我为好友: QQ: 578652607
原文地址:https://www.cnblogs.com/lhghroom/p/10301462.html