使用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("---------------------------------------------------------------")

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章