简单用python的爬取文章生成词云

写之前,大家可以查看什么是robots协议,如何查看这个协议

分2个部分

1.导入需要的库

import requests
from bs4 import BeautifulSoup as bs
import os
import wordcloud as w
import jieba

2.爬虫部分

def getHtml(url):
    h={'user-agent':'Mozilla/5.0'}#防止对方不接受爬虫,掩饰自己浏览器
    try:  
        r=requests.get(url,headers=h)#获取网页内容
        r.encoding=r.apparent_encoding#将网页编码方式呢转换成分析识别的编码方式
        soup=bs(r.text,"lxml")#解析网页
        print(r.status_code)#查看连接代码,如果是200,表示连接成功
        
        xml=soup.findAll('p',style_='')#这里面的东西可以自己设定,具体怎么
        #设定,要自己去看一下网页源码
        print(xml)
        return xml
    except:
        print("出错")

3.文件输出

def htmlToTxt(path,xml):
    print(len(xml))
    if not os.path.exists(path):#创建文件
        with open(path,"w") as f:#根据路径创建文件,文件变量名为f,权限是覆盖写
            for i in range(len(xml)):
                if not xml[i].string is None:#如果P节点编译出来的不是None,就把文件写入
                    f.write(xml[i].string)#写入操作
            f.close() #关闭文件
    else:
    	os.remove(path)
        with open(path,"w") as f:#根据路径创建文件,文件变量名为f,权限是覆盖写
            for i in range(len(xml)):
                if not xml[i].string is None:#如果P节点编译出来的不是None,就把文件写入
                    f.write(xml[i].string)#写入操作
            f.close() #关闭文件

4. 词云图片输出

def txtToPicture(path):
    with open(path,"r") as f:
        t=f.read()#读取文档
        f.close()#关闭文件
        ls=jieba.lcut(t)#分割文档,返回一个列表
        txt=" ".join(ls)
        c=w.WordCloud(font_path  ="msyh.ttc",width=1000,height=700,\
              background_color="white" )#词云图片属性,字体,长宽和背景
        c.generate(txt)#文本处理
        c.to_file("D://0dhshfjhskjhag//out.png")#输出路径

5.主函数

    url=""#自己想爬的网页
    root="D://0dhshfjhskjhag//"#根目录(文件夹名字),里面可以随便更改,最好改独特的名字
    path=root+"政府工作报告.txt"#绝对路径
    if not os.path.exists(root):#如果文件夹不存在,创建文件夹
        os.mkdir(root)

    xml=getHtml(url)
    htmlToTxt(path,xml)
    txtToPicture(path)

6.结语

1.调用主函数
2.主函数里面的url需要自己写
3.第二部分的findall 函数里面的变量需要自己设定

发布了19 篇原创文章 · 获赞 2 · 访问量 2094

猜你喜欢

转载自blog.csdn.net/weixin_43308622/article/details/103488025