本文研究的主要是Python使用requests及BeautifulSoup構建一個網絡爬蟲,具體步驟如下。
功能說明
在Python下面可使用requests模塊請求某個url獲取響應的html文件,接着使用BeautifulSoup解析某個html。
案例
假設我要http://maoyan.com/board/4貓眼電影的top100電影的相關信息,如下截圖:
獲取電影的標題及url。
安裝requests和BeautifulSoup
使用pip工具安裝這兩個工具。
pip install requests
pip install beautifulsoup4
程序
__author__ = 'Qian Yang'
# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
def get_one_page(url):
response= requests.get(url)
if response.status_code == 200:
return response.content.decode("utf8","ignore").encode("gbk","ignore")
#採用BeautifulSoup解析
def bs4_paraser(html):
all_value = []
value = {}
soup = BeautifulSoup(html,'html.parser')
# 獲取每一個電影
all_div_item = soup.find_all('div', attrs={'class': 'movie-item-info'})
for r in all_div_item:
# 獲取電影的名稱和url
title = r.find_all(name="p",attrs={"class":"name"})[0].string
movie_url = r.find_all('p', attrs={'class': 'name'})[0].a['href']
value['title'] = title
value['movie_url'] = movie_url
all_value.append(value)
value = {}
return all_value
def main():
url = 'http://maoyan.com/board/4'
html = get_one_page(url)
all_value = bs4_paraser(html)
print(all_value)
if __name__ == '__main__':
main()
代碼測試可用,實現效果:
最後給大家推薦一個資源很全的python學習聚集地,[點擊進入],這裏有我收集以前學習心得,學習筆記,還有一線企業的工作經驗,且給大定on零基礎到項目實戰的資料,大家也可以在下方,留言,把不懂的提出來,大家一起學習進步
總結
以上就是本文關於Python使用requests及BeautifulSoup構建爬蟲實例代碼的全部內容,希望對大家有所幫助