使用python爬取小说(附python源码)

import requests ###爬虫模块,获取网页文本
import re       ###正则表达式模块,从网页文本中提取所需要的信息
###### gettext(url):输入网站链接 url,返回该网站的文本
def gettext(url):
    r = requests.get(url,timeout=30)
    r.encoding = 'apparent_encoding'
    return r.text
###### 输入目录链接 url,返回各章节链接数组
def geturl(url):
    text=gettext(url)
    chapter_info_list=re.findall(r'<li><a href="(.*?)">',text)
    del(chapter_info_list[0])
    return chapter_info_list
###### 输入网站 url,返回该网站文本数组
def getline(url):
    text = gettext(url)
#print(text,file=open("序章.txt",'a',encoding='utf-8'))
    title=re.findall(r'<h1>(.*?)</h1>',text)
    line=re.findall(r'<span class="calibre[2-9]">(.*?)</span>',text)
    all = title+line
    return(all)
##### 输入数组,生成txt文件
def my_print(line,my_name):
    for i in line:
        print(i+'\n',file=my_name)
##### 主函数
def main():
    my_file=open("龙族.txt",'x',encoding='utf-8')
    url='http://www.yuedu88.com/longzu1/'
    url_list=geturl(url)
    for i in url_list:
        line=getline(i)
        my_print(line,my_file)
main()

2021年2月23日12:39:57

猜你喜欢

转载自blog.csdn.net/Infinity_07/article/details/113982240