当前位置:   article > 正文

用Python爬取某网中小说内容代码分享_python爬虫爬取小说代码

python爬虫爬取小说代码

用Python爬取纵横中文网中小说内容代码分享

这个内容只是纯粹想保留下前几天写的一个小小程序,想想缘由是为了激励学生好好学习。
从这些年对来上课的学生的观察,学生们从原来的刷古装剧到现在的刷娱乐节目,从刷博客到刷短视频,从原来的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')        

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/792278
推荐阅读
相关标签
  

闽ICP备14008679号