Python02:爬取静态网页小说

从小说网站上爬取小说文本,下载到txt文件当中

  1. 获取静态网页上的全部信息
  2. 提取小说文本
  3. 保存小说到.txt文件当中

所需知识:

  1. requests.get()—— 爬取网页信息
  2. BeautifulSoup和正则表达式 ——提取信息
  3. Python文件操作——存储信息

所有程序:


import requests
from bs4 import BeautifulSoup

# =============================================================================
# 1、从网页上获取网页内容(HTML)
# =============================================================================
def getHTMLText(url):  
    try:
        r=requests.get(url)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
        #print(r.text)
    except:
        print("爬取失败")
# =============================================================================
# 2、提取网页内容中合适的信息
# =============================================================================
def getNovelContent(html):
    soup=BeautifulSoup(html,"html.parser")
    text=soup.find_all('div','showtxt')
    text = text[0].text.replace('\xa0'*8,'\n\n    ')
    return text

# =============================================================================
# 3、保存信息到.txt文件中
# =============================================================================
def writeContent(text):
    path= "F://Novels/123.txt"
    fo=open(path,"w",encoding='gb18030',errors='ignore')
    fo.write(text)
    fo.close()

# =============================================================================
# 4、主函数
# =============================================================================
def main():
    url = "http://www.biqukan.com/2_2763/1112188.html"
    html=getHTMLText(url)
    text=getNovelContent(html)
    writeContent(text)
# =============================================================================

main()   

猜你喜欢

转载自blog.csdn.net/weixin_39393712/article/details/79927816
今日推荐