1. 程式人生 > >起點中文網小說爬取-etree,xpath,os

起點中文網小說爬取-etree,xpath,os

tps div html utf requests import bject finally fin

本文章主要是lxml庫的etree解析抽取與xpath解析的應用,還使用了os庫寫文件

import os
import requests
from lxml import etree#lxml庫解析HTML、xml文件抽取想要的數據
#設計模式--面向對象
class Spider(object):
    def start_request(self):
        #1.請求網站拿到數據,抽取小說名創建文件夾,抽取
        response=requests.get(‘https://www.qidian.com/all‘)
        # print(response.text)
        html=etree.HTML(response.text)#結構化
        Bigsrc_list=html.xpath(‘//div[@class="book-mid-info"]/h4/a/@href‘)
        #//:選取元素,而不考慮元素的具體位置;     @:選取屬性
        Bigtit_list=html.xpath(‘//div[@class="book-mid-info"]/h4/a/text()‘)
        # print(Bigsrc_list,Bigtit_list)
        for Bigsrc,Bigtit in zip(Bigsrc_list,Bigtit_list):
            if os.path.exists(Bigtit)==False:#如果不存在文件夾名為該小說名,就創建
                os.mkdir(Bigtit)
            # print(Bigsrc,Bigtit)
            self.file_data(Bigsrc,Bigtit)#調用下一個函數

    def file_data(self, Bigsrc, Bigtit):
        # 2.請求小說,拿到數據,抽取章名,抽取文章鏈接
        response = requests.get("https:" + Bigsrc)#補上缺少的https前綴
        html = etree.HTML(response.text)#etree.HTML可用於在python代碼中嵌入“html文本”。
        listsrc_list = html.xpath(‘//ul[@class="cf"]/li/a/@href‘)
        listtit_list = html.xpath(‘//ul[@class="cf"]/li/a/text()‘)
        for Listsrc, Listtit in zip(listsrc_list, listtit_list):
            # print(Listsrc, Listtit)
            self.finally_file(Listsrc, Listtit,Bigtit)

    def finally_file(self,Listsrc, Listtit,Bigtit):
        # 3.請求文章拿到抽取文章內容,創建文件保存到相應文件夾
        response=requests.get("https:"+Listsrc)
        html=etree.HTML(response.text)#結構化
        content="\n".join(html.xpath(‘//div[@class="read-content j_readContent"]/p/text()‘))
        #S.join()返回一個字符串,元素之間的分隔符是S
        file_name=Bigtit+"\\"+Listtit+".txt"
        #創建Bigtit文件夾下的Listtit.txt文件
        print("正在存儲文件"+file_name)
        with open(file_name,"a",encoding="utf-8")as f:
            f.write(content)
if __name__==‘__main__‘:
    spider = Spider()
    spider.start_request()

  

起點中文網小說爬取-etree,xpath,os