小説の名前とリンクを取る

1514 ワード

次のコードはBeautiful Soupを通じてあるサイトの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 !='
': 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'))