studier_li 2021-09-09 23:12 采纳率: 60%
浏览 67
已结题

python爬小说,报错说正则表达式没有获得正文内容,可是我自己测试4个表达式都是可以提取到内容(测试是在Regexpal网站—成功,爬小说是在pyCharm-报错)


import requests
import re
import os
from multiprocessing.dummy import Pool


start_url = 'https://www.xbiquge.la/58/58814/'

def get_source(url):
    """
    获取网页源代码。
    """
    html = requests.get(url)
    return html.content.decode('utf-8') 


def get_toc(html):
    """
    获取每一章链接,储存到一个列表中并返回。
    """
    toc_url_list = []
    toc_block = re.findall('<dl>(.*?)<div id="footer"', html, re.S)[0]
    toc_url = re.findall("href='(.*?)'", toc_block, re.S)
    for url in toc_url:
        toc_url_list.append(start_url + url)
    return toc_url_list

def get_article(html):
    """
    获取每一章的正文并返回章节名和正文。
    """
    chapter_name = re.search('<title>(.*?)</title>', html, re.S).group(1)
    text_block = re.search('<div id="content">(.*?)</p></div>', html, re.S).group(1)
    text_block = text_block.replace('<br />', '')
    return chapter_name, text_block

def save(chapter, article):
    """
    将每一章保存到本地。
    """
    os.makedirs('白骨大圣', exist_ok=True)  
    with open(os.path.join('白骨大圣', chapter + '.txt'), 'w', encoding='utf-8') as f:
        f.write(article)

def query_article(url):
    """
    根据正文网址获取正文源代码,并调用get_article函数获得正文内容最后保存到本地。
    """
    article_html = get_source(url)
    chapter_name, article_text = get_article(article_html)
    save(chapter_name, article_text)

if __name__ == '__main__':
    toc_html = get_source(start_url)
    toc_list = get_toc(toc_html)
    pool = Pool(4)
    pool.map(query_article, toc_list)



  • 写回答

2条回答 默认 最新

  • CSDN专家-HGJ 2021-09-10 00:08
    关注

    1.增加headers请求头,2 章节网址要改下,3.在text_block部分加上try/except异常处理,防止有的不存在。
    经修改后可正常运行的代码:

    import requests
    import re
    import os
    from multiprocessing.dummy import Pool
    headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38'}
    
    start_url = 'https://www.xbiquge.la/58/58814'
    def get_source(url):
        """
        获取网页源代码。
        """
        html = requests.get(url,headers=headers)
        return html.content.decode('utf-8') 
     
    def get_toc(html):
        """
        获取每一章链接,储存到一个列表中并返回。
        """
        toc_url_list = []
        toc_block = re.findall('<dl>(.*?)<div id="footer"', html, re.S)[0]
        toc_url = re.findall("href='(.*?)'", toc_block, re.S)
        for url in toc_url:
            toc_url_list.append('https://www.xbiquge.la' + url)
        return toc_url_list
    def get_article(html):
        """
        获取每一章的正文并返回章节名和正文。
        """
        chapter_name = re.search('<title>(.*?)</title>', html, re.S).group(1)
        try:
            text_block = re.search('<div id="content">(.*?)</p></div>', html, re.S).group(1)
            text_block = text_block.replace('<br />', '')
        except:text_block=''
        
        return chapter_name, text_block
    def save(chapter, article):
        """
        将每一章保存到本地。
        """
        os.makedirs('白骨大圣', exist_ok=True)  
        with open(os.path.join('白骨大圣', chapter + '.txt'), 'w', encoding='utf-8') as f:
            f.write(article)
    def query_article(url):
        """
        根据正文网址获取正文源代码,并调用get_article函数获得正文内容最后保存到本地。
        """
        article_html = get_source(url)
        chapter_name, article_text = get_article(article_html)
        save(chapter_name, article_text)
    if __name__ == '__main__':
        toc_html = get_source(start_url)
        toc_list = get_toc(toc_html)
        pool = Pool(4)
        pool.map(query_article, toc_list)
    
    

    如有帮助,请点击我回答的右上方采纳按钮给予采纳。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 9月18日
  • 已采纳回答 9月10日
  • 创建了问题 9月9日

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错