爬虫大作业
1.选一个自己感兴趣的主题。
2.用python 编写爬虫程序,从网络上爬取相关主题的数据。
3.对爬了的数据进行文本分析,生成词云。
4.对文本分析结果进行解释说明。
5.写一篇完整的博客,描述上述实现过程、遇到的问题及解决办法、数据分析思想及结论。
6.最后提交爬取的全部数据、爬虫及数据分析源代码。
import requests import re import jieba from bs4 import BeautifulSoup def GetPageContent(ContentUrl): REQUEST = requests.get(ContentUrl) REQUEST.encoding = 'utf-8' SOUP = BeautifulSoup(REQUEST.text, 'html.parser') content=SOUP.select('#cnblogs_post_body')[0].text return content def GetPageInfo(PageUrl): Request=requests.get(PageUrl) Request.encoding='utf-8' Soup = BeautifulSoup(Request.text, 'html.parser') for post_item in Soup.select('.post_item'): if len(post_item.select('.titlelnk')[0])>0: #文章item标题 item_title=post_item.select('.titlelnk')[0].text # 文章item url item_url=post_item.select('a')[0].attrs['href'] return GetPageContent(item_url) #print(item_title) def PrintWordsCount(Text, Top): miss_word = "了|他|说|我|你|就|着|又|的|在|是|有|把|到|也|不|都|她|这|便|去|们|还|但|一个|和|却|里|来|要|没|很|\"" \ "|那|么|一|将|呢|起|于|上|只|得|而|而且|对|所以|见|些|才|从|过|被|并|时|且|给|道|虽然|可以|出" Text = re.sub("[\s+\.\!\/_\",$%^*+—()?【】“《;》”!\-:,。?、~@#¥%……&*();{}=]+", "", Text) Text = re.sub(miss_word + '+', "", Text) words = list(jieba.cut(Text)) key_words = {} for i in set(words): # 统计出词频 key_words[i] = words.count(i) sort_word = sorted(key_words.items(), key=lambda d: d[1], reverse=True) # 排序 for j in range(Top): # 输出 print(sort_word[j]) count='' url='https://www.cnblogs.com/' request=requests.get(url) request.encoding='utf-8' soup=BeautifulSoup(request.text,'html.parser') page=int(soup.select('.pager')[0].select('a')[-8].text) for i in range(1,8): count+=GetPageInfo('https://www.cnblogs.com/#p{}'.format(i)) PrintWordsCount(count,10)