真的不想再看见有谁未经许可也不标明出处搬运我的文章了,所以我自己先在博客园同步发一个。
进入正题,首先要搞到资源,我先去了搜索了一番,找到个网站“落霞”。一言不合就按下了F12,翻了下网页源码,超级简单。
1 from bs4 import BeautifulSoup
2 from requests import Session
3 from re import sub,DOTALL
4 sess = Session()
5 txt=[]
6 url = 'https://www.luoxia.com/qing/48416.htm'
7 def find(url):
8 res = sess.get(url)
9 soup = BeautifulSoup(res.content,'html.parser')
10 title = soup.find('title')
11 div = soup.find('div',id='nr1')
12 ps = div.find_all('p')
13 page = title.text+'\n'
14 print(page)
15 for p in ps:
16 page += p.text+'\n'
17 txt.append(page)
18 try:
19 a = soup.find('a',rel='next')
20 href = a['href']
21 except:
22 return 0
23 find(href)
24 find(url)
网页结构真的超级简洁有规律,标题就在里,正文在一个title标签里,而且每段话都用p标签包起来了。不过他的网址不是连续的数字,so,迭代大法。下一章的链接就包在一个a标签里,还带了属性。给落霞网站程序员打call,不过我马上就后悔了,这个网站速度有点慢,差不多一秒一章的样子?
是我换了个网站,书趣阁,这个倒是快,就是程序员不喜欢打标记。
1 url = '17754382.html'
2 shu = []
3 def shuquge(url):
4 res = sess.get('http://www.shuquge.com/txt/83203/'+url)
5 soup = BeautifulSoup(res.content,'html.parser')
6 h1 = soup.find('h1')
7 div = soup.find('div', id="content")
8 page = str(div)
9 page = page.replace('<div class="showtxt" id="content">','')
10 page = page.replace('<br/>','')
11 page = sub('http.*','',page,0,DOTALL)
12 shu.append(h1.text+'\n'+page)
13 print(h1.text)
14 href = [i['href'] for i in soup.find_all('a') if i.text == '下一章'][0]
15 if 'index' not in href:
16 shuquge(href)
17 shuquge(url)
标签都没个正经属性,还一堆广告。正文里面也有,还得我删
1 import jieba,cv2
2 from wordcloud import WordCloud
3 img=cv2.imread('c2cec1e832a833ded3f6f9bbc226ae2f.jpeg')
4 content=' '.join(jieba.cut(''.join(shu)))
5 wordshow = WordCloud(background_color='white',
6 width=800,
7 height=800,
8 max_words=800,
9 max_font_size=100,
10 font_path="msyh.ttc", #用微软雅黑作为字体显示效果
11 mask=img,
12 mode='RGBA'
13 ).generate(content)
14 wordshow.to_file('word.png') #转换成图片
其实本来只想下载小说的,闲着也是闲着,吃饱了也是撑着,不如来写程序,我和身边的朋友都在做,每天收入0元。
对了,保存一下
1 from codecs import open
2 with open('庆余年.txt','w','utf8')as f:
3 f.write('\n'.join(shu))#网页是utf8的,windows下直接用gbk存不了

来源:https://www.cnblogs.com/szh1213/p/12243961.html