Home Backend Development Python Tutorial python 解析html之BeautifulSoup

python 解析html之BeautifulSoup

Jun 06, 2016 am 11:26 AM
beautifulsoup html python

代码如下:


# coding=utf-8
from BeautifulSoup import BeautifulSoup, Tag, NavigableString
from SentenceSpliter import SentenceSpliter
from os.path import basename,dirname,isdir,isfile
from os import makedirs
from shutil import copyfile
import io
import time
import re

class build_tpl:
    def __init__(self,parse_file,build_tpl_name,cp_pic_dir,show_pic_dir,js_path,set_lang=2052):
        '''参数说明:解析文件名,模版名称,保存图片路径,图片显示路径,js路径,当前语言(分句使用)'''

        #取得解析文件目录路径
        if len(dirname(parse_file))>1:
            self.cur_dir = dirname(parse_file)+"/";
        else:
            self.cur_dir ="./";

        #建立的模版文件文件名
        self.build_tpl_name = build_tpl_name;
        #图片cp到得目录
        self.cp_pic_dir = cp_pic_dir;
        #通过http展现图片的目录
        self.show_pic_dir = show_pic_dir;
        #加载js的路径
        self.js_path = js_path;

        #句段组
        self.get_text_arr = [];
        #当前图片名数组
        self.cur_pic_arr = [];

        #解析文件 取得soup 资源
        self.soup = self.get_soup(parse_file);
        #取得html文档中,段文档
        self.get_text_arr = self.soup.body.findAll(text=lambda(x): len(x.strip()) > 0);
        #取得句对
        self.get_sentence_arr = self.parse_text(self.get_text_arr,set_lang);
        #取得替换数组
        self.replace_list = self.get_replace_list(self.get_text_arr,set_lang);
        #取得图片数组
        self.cur_pic_arr = self.soup.findAll('img');

        #self.write_file_by_list("no.txt",self.get_text_arr);
        #self.write_file_by_list("yes.txt",self.get_sentence_arr);

    #保存词组到文件
    def save_data_file(self):
        file_name = self.build_tpl_name+".data";
        self.write_file_by_list(file_name,self.get_data());
    #取得词组
    def get_data(self):
        return self.get_sentence_arr;
    #数组写入到文档
    def write_file_by_list(self,file_name,write_arr):
        file=io.FileIO(file_name,"w");
        file.write(('\n'.join(write_arr)).encode('utf-8'));
        file.close();
    #字符串写入到文档
    def write_file(self,file_name,file_contents):
        file=io.FileIO(file_name,"w");
        file.write(file_contents.encode('utf-8'));
        file.close();
    #建立图片hash目录
    def get_pic_hash(self):
        return time.strftime("%Y/%m/%d/");
    #建立模版文件
    def builder(self):
        #没能发生替换的单词
        bug_msg = [];
        #进行内容模版替换
        for i in range(len(self.get_text_arr)):
            #替换
            rep_str = "$rep_arr[{0}]".format(i);
            try:
                self.soup.body.find(text=self.get_text_arr[i]).replaceWith(self.replace_list[i]);
            except AttributeError:
                bug_msg.append(self.get_text_arr[i]);

        #取得图片hash路径
        hash_dir = self.get_pic_hash();
        #构造展示图片路径
        show_pic_dir = self.show_pic_dir+hash_dir;
        #构造图片保存路径
        cp_pic_dir = self.cp_pic_dir+hash_dir;

        #判断保存图片的目录是否存在 不存在建立
        if not isdir(cp_pic_dir):
            makedirs(cp_pic_dir);

        for pic_name in self.cur_pic_arr:
            #进行图片路径替换
            old_pic_src = pic_name['src'];
            pic_name['src'] = show_pic_dir+old_pic_src;
            #进行图片拷贝
            cp_src_file = self.cur_dir+old_pic_src;
            cp_dis_file = cp_pic_dir+old_pic_src;
            copyfile(cp_src_file,cp_dis_file);

        #建立bug信息的文档
        #self.write_file_by_list("bug.txt",bug_msg);

        #添加js
        tag = Tag(self.soup,"script");
        tag['type'] = "text/javascript";
        tag['src'] =self.js_path+"jquery.js";

        tag2 = Tag(self.soup,"script");
        tag2['type'] = "text/javascript";
        tag2['src'] =self.js_path+"init.js";

        self.soup.head.insert(2,tag2);
        self.soup.head.insert(2,tag);


        #建立模版
        self.write_file(self.build_tpl_name,self.soup);
    #取得替换的html文件    
    def get_replace_html(self,rep_id,rep_data=""):
        '''
        参数说明:替换id,替换内容(为空的采用模版模式替换)
        '''
        if len(rep_data) > 0 :
            rep_str = rep_data;
        else:
            rep_str = "$rep_arr[{0}]".format(rep_id);
        return ""+rep_str+"";
    #取得替换数组
    def get_replace_list(self,text_arr,set_lang):
        Sp = SentenceSpliter();
        Sp.SetLang(set_lang);
        temp_sentence = [];
        jump_i = 0;
        for text in text_arr:
            SList = Sp.Split(text);
            replace_temp = "";
            if SList != None:
                for item in SList:
                    replace_temp = replace_temp+self.get_replace_html(jump_i,item);
                    jump_i=jump_i+1;
            else:
                replace_temp = self.get_replace_html(jump_i,text);
                jump_i=jump_i+1;
            temp_sentence.append(replace_temp);
        return temp_sentence;
    #分句
    def parse_text(self,text_arr,set_lang):
        Sp = SentenceSpliter();
        Sp.SetLang(set_lang);
        temp_sentence = [];
        for text in text_arr:
            SList = Sp.Split(text);
            if SList != None:
                for item in SList:
                    temp_sentence.append(item);
            else:
                temp_sentence.append(text);

        return temp_sentence;

    #取得解析资源
    def get_soup(self,parse_file):
        try:
            file=io.FileIO(parse_file,"r");
            doc = file.readall();
            file.close();
        except IOError:
            print 'ERROR: %s file not found!' %parse_file;
            return False;
        #开始解析html文档
        return BeautifulSoup(''.join(doc));

if __name__ == "__main__":
    from sys import argv, exit;

    if len(argv)         print "USAGE: python %s " % argv[0]
        exit(255);

    if not isfile(argv[1]):
        print "no such input file: %s" % argv[1]
        exit(1)


    paser_file = argv[1];#"html/testpic.html";
    tpl_file = argv[2];
    save_pic_path = argv[3];
    show_pic_path = argv[4];
    load_js_path = argv[5];
    #解析开始 设置解析文件,模版名,图片保存路径,图片显示路径
    so = build_tpl(paser_file,tpl_file,save_pic_path,show_pic_path,load_js_path);
    #建立模版
    so.builder();
    #保存分句的句对
    so.save_data_file();

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

Solutions to the service that cannot be started after MySQL installation Solutions to the service that cannot be started after MySQL installation Apr 08, 2025 am 11:18 AM

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration

MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

See all articles