从中国古籍全录网站抓取文章并自动按章节名存储为TXT---带模拟登陆加强版,抓取txt---,昨天发过一个不成熟的版本


昨天发过一个不成熟的版本,古籍里的非标准字符解析报错问题、未登录抓不了全文问题、抓取的文本中残留网页代码问题都没有解决,这个版本已经解决了上述问题,并且加入了可以自行输入用户名和密码的功能(要自己去网站注册好),并且添加了两条删除正文中夹杂的网页源码的代码.做这个程序的过程中真的学到好多.............在此特别感谢 @美好的2014 大大的建议,GB18030使字符无法解码问题得到了完美解决。

#-*- coding:GB18030 -*-import osimport re  import urllib.requestimport http.cookiejarimport hashliburllogin = 'http://bbs.artx.cn/logging.php?action=login&loginsubmit=yes&inajax=1'cj = http.cookiejar.CookieJar()#建立新的openeropener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))#装载新的openerurllib.request.install_opener(opener)#盛放PostData的字典postDict = {            'formhash' : '00e0e70f',            'referer' : 'http%3A%2F2Fguji.artx.cn%2F',            'loginfield' : 'username',            'username' : 'username',            'password' : 'password',            'questionid' : '0',            'answer' : '',            'cookietime' : '2592000',            }#输入用户名,并加入POST字典postDict['username'] = input('请输入用户名:\\n')md5 = hashlib.md5()password = input('请输入密码:\\n')#将输入的密码转换为MD5,MD5.update只接受bytemd5.update(bytearray(password.encode('utf-8')))#把转换后的密码加入POST字典postDict['password'] = md5.hexdigest()#将字典中的PostData编译成url格式,再转码为UTF-8postData = urllib.parse.urlencode(postDict).encode('utf-8')#带着PostData访问登录页面resp = urllib.request.urlopen(urllogin, postData)html = resp.read()#据观察,该页面编码格式为GBK,所以此处以GBK解码uhtml = html.decode('gbk')#获取登录成功信息,失败信息就不做了,反正我没登录失败过....message = re.findall('(?<=innerHTML = \\'<p>).*(?=</p>\\';)',uhtml,re.DOTALL)print (message[0])#处理书籍主页面URLdef dealurl():    url = input("请输入要抓取的文章主页面的地址:\\n")    response = urllib.request.urlopen(url)    html = response.read()    #将html解码出来    uhtml = html.decode('utf-8')    #截取所有章节页面的URL    urls = re.findall('(?<=<li><a href=\\").*\\.html(?=\\">)',uhtml)      #截取所有章节标题    titles = re.findall('(?<=\\.html\\">).*(?=</a></li>)',uhtml)    #截取文章总标题    titleinlist = re.findall('(?<=title"><h3>).*(?=</h3></div>)',uhtml)    #截取文章所属的库    kuinlist = re.findall('(?<=\\.html>).库(?=\\</a> )',uhtml)     ku = kuinlist[0]    title = titleinlist[0]    print ("URL列表:\\n",urls)    print ("章节列表:\\n",titles)    if len(urls) == len(titles):        num = len(urls)        print ("解析出的链接数和章节数相等,匹配正确!\\n")        print ("序章正文内容:\\n",text(uhtml))        dealurl2(url,'简介',title,ku)        for i in range(num):            url1 = urls[i]            title1 = titles[i]            dealurl2("http://guji.artx.cn" + url1,title1,title,ku)    else:        print ("解析出的章节数和链接数不相等,可能存在错误!\\n")    dealurl()#处理文本def text(i):     #大致截取出正文文本    text1 = re.findall('(?<=font-size:14px;\\">).*?(?=</div>)',i,re.DOTALL)    #删除文本中的阅读笔记代码    garbages1 = re.findall('<font class=bj_style>.*?</a></font>',text1[0],re.DOTALL)    for g1 in garbages1:        text1[0] = text1[0].replace(g1,'\\n')    #删除文本中的‘中国古籍全录’代码    garbages2 = re.findall('<a href=.http.*?</a>',text1[0],re.DOTALL)    for g2 in garbages2:        text1[0] = text1[0].replace(g2,'')    #删除文本中剩余的<br>    text1[0] = text1[0].replace("<br>","")    if text1[0].count("&nbsp") == 0:         pass    else:        text1[0] = text1[0].replace(" ",' ')     return text1[0]#处理子页面,i是url,n是章节名,m是书的总标题,k书籍所属库def dealurl2(i,n,m,k):     response1 = urllib.request.urlopen(i)    html1 = response1.read()    uhtml1 = html1.decode('utf-8')    #判断以库名和书名命名的文件夹是否存在,若不存在则创建    if os.path.exists('E:/downloadedbooks/' + k + '/' + m) == False:        os.makedirs('E:/downloadedbooks/' + k + '/' + m)    else:        pass    #获取文章内容    article = text(uhtml1)    #在目录下以书名为文件名,以GB18030为默认编码创建TXT并写入内容    f = open('E:/downloadedbooks/' + k + '/' + m + '/' + n + '.txt','w',encoding='GB18030')    f.write(str(article))    print (n,'.........下载完成.')    f.close()dealurl()#该片段来自于http://byrx.net

评论关闭