赞
踩
这个内容只是纯粹想保留下前几天写的一个小小程序,想想缘由是为了激励学生好好学习。
从这些年对来上课的学生的观察,学生们从原来的刷古装剧到现在的刷娱乐节目,从刷博客到刷短视频,从原来的CS游戏到现在的看小说看王者,虽然爱好在变,但是对信息技术学科的爱好仍然只停留在对信息技术机房的网络环境的爱好这个无奈的现状下。
上周开始学循环了,循环是一个让很多同学头疼的知识点,看不到在课堂上程序可以干嘛。只能写写那些小学数学计算判断题吗?于是投其所好,针对学生们对看小说的热爱,写了这个爬虫程序,告诉他们,学习是为了能在以后能更好阅读理解并运用网络上网友们的程序,达到利用计算机程序解决问题的目的。
下方附代码,写得比较粗糙,勿喷。
import urllib.request from bs4 import BeautifulSoup import re def getData(url): head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36" } request = urllib.request.Request(url, headers=head) response = urllib.request.urlopen(request) html = response.read().decode('utf-8') return html def saveFile(html, name): path = open(f'test/{name}.txt', 'w', encoding='utf-8') # 已写入的方式创建文件 path.write(html) # 写入爬下的信息 path.close() # 关闭文件 #findname = re.compile(r'<a (.*?) src="(.*?)"', re.S) findtitle = re.compile(r'<a (.*?)>(.*?)</a>') if __name__ == "__main__": url = "http://book.*****.com/showchapter/921241.html" #此处屏蔽具体网址,不然不给发啊 html = getData(url) #print(html) soup=BeautifulSoup(html , "html5lib") lit = soup.find_all("li",class_ = 'col-4') #print(lit) j = 1 urllist = [] content="" try: for item in lit: filetitle = re.findall(findtitle,str(item)) urllist.append(filetitle[0][0][6:59]) #print(filetitle[0][0][6: 59]) urlx = filetitle[0][0][6: 59] htmlx = getData(urlx) soupx = BeautifulSoup(htmlx, "html5lib") lix = soupx.find_all("div", class_='content') print(lix[0]) content = content + str(filetitle[0][1]) + str(lix[0]) j = j + 1 except: print("第",j,"章是新的一章") content = content.replace("<div class=\"content\" itemprop=\"acticleBody\">"," ") content = content.replace("<div>"," ") content = content.replace("</div>", "\n") content = content.replace("<p>", " ") content = content.replace("</p>", "\n") saveFile(content, 'story')
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。