溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python使用requests及BeautifulSoup構(gòu)建爬蟲實(shí)例代碼

發(fā)布時(shí)間:2020-09-27 21:21:28 來源:腳本之家 閱讀:174 作者:sober_qianyang 欄目:開發(fā)技術(shù)

本文研究的主要是Python使用requests及BeautifulSoup構(gòu)建一個(gè)網(wǎng)絡(luò)爬蟲,具體步驟如下。

功能說明

在Python下面可使用requests模塊請求某個(gè)url獲取響應(yīng)的html文件,接著使用BeautifulSoup解析某個(gè)html。

案例

假設(shè)我要http://maoyan.com/board/4貓眼電影的top100電影的相關(guān)信息,如下截圖:

Python使用requests及BeautifulSoup構(gòu)建爬蟲實(shí)例代碼

獲取電影的標(biāo)題及url。

安裝requests和BeautifulSoup

使用pip工具安裝這兩個(gè)工具。

pip install requests

Python使用requests及BeautifulSoup構(gòu)建爬蟲實(shí)例代碼

pip install beautifulsoup4

Python使用requests及BeautifulSoup構(gòu)建爬蟲實(shí)例代碼

程序

__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')
  # 獲取每一個(gè)電影
  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()

代碼測試可用,實(shí)現(xiàn)效果:

Python使用requests及BeautifulSoup構(gòu)建爬蟲實(shí)例代碼

總結(jié)

以上就是本文關(guān)于Python使用requests及BeautifulSoup構(gòu)建爬蟲實(shí)例代碼的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI