Python使用requests及BeautifulSoup構(gòu)建爬蟲實(shí)例代碼
本文研究的主要是Python使用requests及BeautifulSoup構(gòu)建一個(gè)網(wǎng)絡(luò)爬蟲,具體步驟如下。
功能說明
在Python下面可使用requests模塊請(qǐng)求某個(gè)url獲取響應(yīng)的html文件,接著使用BeautifulSoup解析某個(gè)html。
案例
假設(shè)我要http://maoyan.com/board/4貓眼電影的top100電影的相關(guān)信息,如下截圖:
獲取電影的標(biāo)題及url。
安裝requests和BeautifulSoup
使用pip工具安裝這兩個(gè)工具。
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') # 獲取每一個(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()
代碼測(cè)試可用,實(shí)現(xiàn)效果:
總結(jié)
以上就是本文關(guān)于Python使用requests及BeautifulSoup構(gòu)建爬蟲實(shí)例代碼的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
- Python爬蟲庫(kù)requests獲取響應(yīng)內(nèi)容、響應(yīng)狀態(tài)碼、響應(yīng)頭
- python中數(shù)據(jù)爬蟲requests庫(kù)使用方法詳解
- python爬蟲入門教程--優(yōu)雅的HTTP庫(kù)requests(二)
- Python3網(wǎng)絡(luò)爬蟲中的requests高級(jí)用法詳解
- python爬蟲基礎(chǔ)教程:requests庫(kù)(二)代碼實(shí)例
- Python 通過requests實(shí)現(xiàn)騰訊新聞抓取爬蟲的方法
- 使用requests庫(kù)制作Python爬蟲
- Python爬蟲工具requests-html使用解析
相關(guān)文章
python等差數(shù)列求和公式前 100 項(xiàng)的和實(shí)例
今天小編就為大家分享一篇python等差數(shù)列求和公式前 100 項(xiàng)的和實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-02-02Python?input輸入超時(shí)選擇默認(rèn)值自動(dòng)跳過問題
這篇文章主要介紹了Python?input輸入超時(shí)選擇默認(rèn)值自動(dòng)跳過問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02Python matplotlib 繪制雙Y軸曲線圖的示例代碼
Matplotlib是非常強(qiáng)大的python畫圖工具,這篇文章主要介紹了Python matplotlib 繪制雙Y軸曲線圖,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06python的pygal模塊繪制反正切函數(shù)圖像方法
在本篇文章中我們給大家整理了關(guān)于如何用python的pygal模塊繪制反正切函數(shù)圖像的知識(shí)點(diǎn)內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。2019-07-07