美文网首页
爬取小说名字和链接

爬取小说名字和链接

作者: Actimermao | 来源:发表于2017-09-26 15:48 被阅读0次

    下面的代码是通过BeautifulSoup解析某个网站的html代码,然后通过特定标签实现爬取该网站上的小说名字和链接。

    from bs4 import BeautifulSoup
    from urllib import request
    
    if __name__ == '__main__':
        target_url = 'http://www.biqukan.com/1_1094/'
        req = request.Request(target_url)
        response = request.urlopen(req)
        response = response.read().decode('gbk')
        #print(response)
        soup = BeautifulSoup(response,'lxml')#将response用BeautifulSoup按照lxml的格式解析,得到一个BeautifulSoup对象
                                                                    #并能按照标准的缩进格式的结构输出
        #print(soup.prettify())     #结构化输出
        #搜索建立的文档树,找出来div标签中class是listmain的所有子标签
        chapter = soup.find_all('div', class_ = 'listmain')
        #使用查询结果在此创建一个BeautifulSoup对象,继续对其解析
        download_soup = BeautifulSoup(str(chapter),'lxml')
        print(download_soup.prettify())
        flag = False
        #遍历dl标签下的所有子节点 children只包含直接子节点
        for child in download_soup.dl.children:
            #过滤掉回车,(这个地方为什么会有空行暂时不太理解,回头再研究)
            if child !='\n':
    
                if child.string == '《一念永恒》正文卷':
                    flag = True
                if flag == True and child.a != None:
                    download_url = "http://www.biqukan.com" + child.a.get('href')
                    download_name = child.string
                    print(download_name, ': ',download_url)
       # for b in soup.find_all('a'):
            #print(b['href'],b.string)
        #print(soup.find_all('a'))
    

    相关文章

      网友评论

          本文标题:爬取小说名字和链接

          本文链接:https://www.haomeiwen.com/subject/srgsextx.html