1. 程式人生 > >使用beautifulsoup做一個簡單的網路爬蟲

使用beautifulsoup做一個簡單的網路爬蟲

爬取網站:http://www.yc.ifeng.com/?cid=91002

爬取結果

 

首先我們來看看F12之後,要爬取的標籤 table>tbody>tr>td 中的內容。有的還要更深層次的挖掘

 

首先我們先找到id為booklist的標籤。一開始我再猶豫要不要一層一層來找。通過tbody>tr>td>a>...來找。但是最後都沒成功(可能是我的技術的問題)。最後上網查了資料發現,其實沒必要一層一層來。就直接找你想要的那個標籤。例如我想找書名。

首先 main_tag=soup.find_all('div', id='book_list')#查詢 id為 book_list 查詢最外層

main_tag_list=main_tag[0].find_all('tr') #查詢tr層 因為一會要迴圈。有多少行,就迴圈多少次

for name_item in it.find_all('td', class_='col-name'):

        for name_i in name_item.find_all('a',class_='bookt'): #查詢a標籤,且類名是bookt

            name_dict['name'] = name_i['title']#獲取title

            name_list.append(name_dict)

 

完整程式碼:

from  urllib  import  request
from bs4 import BeautifulSoup as bs

resp=request.urlopen('http://www.yc.ifeng.com/?cid=91002')
html_data=resp.read().decode()

soup=bs(html_data, 'html.parser')
main_tag=soup.find_all('div', id='book_list')#查詢 id為 book_list

main_tag_list=main_tag[0].find_all('tr')
#main_tag_list=main_tag.tbody.children
type_list=[]#型別列表
name_list=[]#書名列表
author_list=[]#作者列表
book_state_list=[]#圖書狀態
update_time_list=[]#更新事件

for it in main_tag_list:
    type_dict = {}
    name_dict = {}
    author_dict = {}
    update_time={}
    book_state={}
    for name_item in it.find_all('td',class_='col-time'):#查詢td 且類名為col-time
        update_time['update_time']=name_item.text #獲得內容
        update_time_list.append(update_time)
    for name_item in it.find_all('td',class_='col-state'):
        book_state['book_state']=name_item.text
        book_state_list.append(book_state)
    for name_item in it.find_all('td',class_='col-type'):
        for type_i in name_item.find_all('a'):
            type_dict['type']=type_i['title'] #獲得標籤裡的內容
            type_list.append(type_dict)
    for name_item in it.find_all('td', class_='col-name'):
        for name_i in name_item.find_all('a',class_='bookt'):
            name_dict['name'] = name_i['title']
            name_list.append(name_dict)
    for name_item in it.find_all('td', class_='col-author'):
        for author_i in name_item.find('a'):
            author_dict['author'] = author_i
            author_list.append(author_dict)

print("---------------------------------------------------------------")
print(len(type_list))
for i in range(len(type_list)):
    print(type_list[i],name_list[i],author_list[i],update_time_list[i],book_state_list[i])
print("---------------------------------------------------------------")