Python7個(gè)爬蟲(chóng)小案例詳解(附源碼)中篇
本次的7個(gè)python爬蟲(chóng)小案例涉及到了re正則、xpath、beautiful soup、selenium等知識(shí)點(diǎn),非常適合剛?cè)腴T(mén)python爬蟲(chóng)的小伙伴參考學(xué)習(xí)。
前言
關(guān)于Python7個(gè)爬蟲(chóng)小案例的文章分為三篇,本篇為中篇,共兩題,其余兩篇內(nèi)容請(qǐng)關(guān)注!
題目三:
分別使用XPath和Beautiful Soup4兩種方式爬取并保存非異步加載的“豆瓣某排行榜”如https://movie.douban.com/top250的名稱(chēng)、描述、評(píng)分和評(píng)價(jià)人數(shù)等數(shù)據(jù)
先分析:
首先,來(lái)到豆瓣Top250頁(yè)面,首先使用Xpath版本的來(lái)抓取數(shù)據(jù),先分析下電影列表頁(yè)的數(shù)據(jù)結(jié)構(gòu),發(fā)下都在網(wǎng)頁(yè)源代碼中,屬于靜態(tài)數(shù)據(jù)
接著我們找到數(shù)據(jù)的規(guī)律,使用xpath提取每一個(gè)電影的鏈接及電影名
然后根據(jù)鏈接進(jìn)入到其詳情頁(yè)
分析詳情頁(yè)的數(shù)據(jù),發(fā)現(xiàn)也是靜態(tài)數(shù)據(jù),繼續(xù)使用xpath提取數(shù)據(jù)
最后我們將爬取的數(shù)據(jù)進(jìn)行存儲(chǔ),這里用csv文件進(jìn)行存儲(chǔ)
接著是Beautiful Soup4版的,在這里,我們直接在電影列表頁(yè)使用bs4中的etree進(jìn)行數(shù)據(jù)提取
最后,同樣使用csv文件進(jìn)行數(shù)據(jù)存儲(chǔ)
源代碼即結(jié)果截圖:
XPath版:
import re from time import sleep import requests from lxml import etree import random import csv def main(page,f): url = f'https://movie.douban.com/top250?start={page*25}&filter=' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.35 Safari/537.36',} resp = requests.get(url,headers=headers) tree = etree.HTML(resp.text) # 獲取詳情頁(yè)的鏈接列表 href_list = tree.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[1]/a/@href') # 獲取電影名稱(chēng)列表 name_list = tree.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[2]/div[1]/a/span[1]/text()') for url,name in zip(href_list,name_list): f.flush() # 刷新文件 try: get_info(url,name) # 獲取詳情頁(yè)的信息 except: pass sleep(1 + random.random()) # 休息 print(f'第{i+1}頁(yè)爬取完畢') def get_info(url,name): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.35 Safari/537.36', 'Host': 'movie.douban.com', } resp = requests.get(url,headers=headers) html = resp.text tree = etree.HTML(html) # 導(dǎo)演 dir = tree.xpath('//*[@id="info"]/span[1]/span[2]/a/text()')[0] # 電影類(lèi)型 type_ = re.findall(r'property="v:genre">(.*?)</span>',html) type_ = '/'.join(type_) # 國(guó)家 country = re.findall(r'地區(qū):</span> (.*?)<br',html)[0] # 上映時(shí)間 time = tree.xpath('//*[@id="content"]/h1/span[2]/text()')[0] time = time[1:5] # 評(píng)分 rate = tree.xpath('//*[@id="interest_sectl"]/div[1]/div[2]/strong/text()')[0] # 評(píng)論人數(shù) people = tree.xpath('//*[@id="interest_sectl"]/div[1]/div[2]/div/div[2]/a/span/text()')[0] print(name,dir,type_,country,time,rate,people) # 打印結(jié)果 csvwriter.writerow((name,dir,type_,country,time,rate,people)) # 保存到文件中 if __name__ == '__main__': # 創(chuàng)建文件用于保存數(shù)據(jù) with open('03-movie-xpath.csv','a',encoding='utf-8',newline='')as f: csvwriter = csv.writer(f) # 寫(xiě)入表頭標(biāo)題 csvwriter.writerow(('電影名稱(chēng)','導(dǎo)演','電影類(lèi)型','國(guó)家','上映年份','評(píng)分','評(píng)論人數(shù)')) for i in range(10): # 爬取10頁(yè) main(i,f) # 調(diào)用主函數(shù) sleep(3 + random.random())
Beautiful Soup4版:
import random import urllib.request from bs4 import BeautifulSoup import codecs from time import sleep def main(url, headers): # 發(fā)送請(qǐng)求 page = urllib.request.Request(url, headers=headers) page = urllib.request.urlopen(page) contents = page.read() # 用BeautifulSoup解析網(wǎng)頁(yè) soup = BeautifulSoup(contents, "html.parser") infofile.write("") print('爬取豆瓣電影250: \n') for tag in soup.find_all(attrs={"class": "item"}): # 爬取序號(hào) num = tag.find('em').get_text() print(num) infofile.write(num + "\r\n") # 電影名稱(chēng) name = tag.find_all(attrs={"class": "title"}) zwname = name[0].get_text() print('[中文名稱(chēng)]', zwname) infofile.write("[中文名稱(chēng)]" + zwname + "\r\n") # 網(wǎng)頁(yè)鏈接 url_movie = tag.find(attrs={"class": "hd"}).a urls = url_movie.attrs['href'] print('[網(wǎng)頁(yè)鏈接]', urls) infofile.write("[網(wǎng)頁(yè)鏈接]" + urls + "\r\n") # 爬取評(píng)分和評(píng)論數(shù) info = tag.find(attrs={"class": "star"}).get_text() info = info.replace('\n', ' ') info = info.lstrip() print('[評(píng)分評(píng)論]', info) # 獲取評(píng)語(yǔ) info = tag.find(attrs={"class": "inq"}) if (info): # 避免沒(méi)有影評(píng)調(diào)用get_text()報(bào)錯(cuò) content = info.get_text() print('[影評(píng)]', content) infofile.write(u"[影評(píng)]" + content + "\r\n") print('') if __name__ == '__main__': # 存儲(chǔ)文件 infofile = codecs.open("03-movie-bs4.txt", 'a', 'utf-8') # 消息頭 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'} # 翻頁(yè) i = 0 while i < 10: print('頁(yè)碼', (i + 1)) num = i * 25 # 每次顯示25部 URL序號(hào)按25增加 url = 'https://movie.douban.com/top250?start=' + str(num) + '&filter=' main(url, headers) sleep(5 + random.random()) infofile.write("\r\n\r\n") i = i + 1 infofile.close()
題目四:
實(shí)現(xiàn)某東商城某商品評(píng)論數(shù)據(jù)的爬?。ㄔu(píng)論數(shù)據(jù)不少于100條,包括評(píng)論內(nèi)容、時(shí)間和評(píng)分)
先分析:
本次選取的某東官網(wǎng)的一款聯(lián)想筆記本電腦,數(shù)據(jù)為動(dòng)態(tài)加載的,通過(guò)開(kāi)發(fā)者工具抓包分析即可。
源代碼及結(jié)果截圖:
import requests import csv from time import sleep import random def main(page,f): url = 'https://club.jd.com/comment/productPageComments.action' params = { 'productId': 100011483893, 'score': 0, 'sortType': 5, 'page': page, 'pageSize': 10, 'isShadowSku': 0, 'fold': 1 } headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.35 Safari/537.36', 'referer': 'https://item.jd.com/' } resp = requests.get(url,params=params,headers=headers).json() comments = resp['comments'] for comment in comments: content = comment['content'] content = content.replace('\n','') comment_time = comment['creationTime'] score = comment['score'] print(score,comment_time,content) csvwriter.writerow((score,comment_time,content)) print(f'第{page+1}頁(yè)爬取完畢') if __name__ == '__main__': with open('04.csv','a',encoding='utf-8',newline='')as f: csvwriter = csv.writer(f) csvwriter.writerow(('評(píng)分','評(píng)論時(shí)間','評(píng)論內(nèi)容')) for page in range(15): main(page,f) sleep(5+random.random())
到此這篇關(guān)于Python7個(gè)爬蟲(chóng)小案例詳解(附源碼)中篇的文章就介紹到這了,其他兩個(gè)部分的內(nèi)容(上、下篇)請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python7個(gè)爬蟲(chóng)小案例詳解(附源碼)下篇
- Python7個(gè)爬蟲(chóng)小案例詳解(附源碼)上篇
- 利用Python爬蟲(chóng)爬取金融期貨數(shù)據(jù)的案例分析
- Python爬蟲(chóng)采集Tripadvisor數(shù)據(jù)案例實(shí)現(xiàn)
- Python?Ajax爬蟲(chóng)案例分享
- Python爬蟲(chóng)入門(mén)案例之爬取去哪兒旅游景點(diǎn)攻略以及可視化分析
- Python爬蟲(chóng)入門(mén)案例之爬取二手房源數(shù)據(jù)
- Python爬蟲(chóng)入門(mén)案例之回車(chē)桌面壁紙網(wǎng)美女圖片采集
- Python爬蟲(chóng)之Scrapy環(huán)境搭建案例教程
- 用Python爬蟲(chóng)破解滑動(dòng)驗(yàn)證碼的案例解析
- python爬蟲(chóng)系列網(wǎng)絡(luò)請(qǐng)求案例詳解
- python爬蟲(chóng)破解字體加密案例詳解
- python爬蟲(chóng)線程池案例詳解(梨視頻短視頻爬取)
- python爬蟲(chóng)scrapy框架的梨視頻案例解析
- python爬蟲(chóng)利器之requests庫(kù)的用法(超全面的爬取網(wǎng)頁(yè)案例)
- Python爬蟲(chóng)實(shí)戰(zhàn)案例之爬取喜馬拉雅音頻數(shù)據(jù)詳解
- Python爬蟲(chóng)Scrapy框架CrawlSpider原理及使用案例
- Python爬蟲(chóng)之對(duì)CSDN榜單進(jìn)行分析
相關(guān)文章
Python+selenium破解拼圖驗(yàn)證碼的腳本
很多網(wǎng)站在登錄或者注冊(cè)時(shí)都會(huì)遇到拼圖驗(yàn)證碼,這種拼圖驗(yàn)證碼實(shí)際上是多個(gè)小碎片經(jīng)過(guò)重新組合成的一張整體。本文將和大家分享一個(gè)基于Python selenium的破解拼圖驗(yàn)證碼的腳本,需要的可以參考一下2022-02-02全面了解Python環(huán)境配置及項(xiàng)目建立
下面小編就為大家?guī)?lái)一篇全面了解Python環(huán)境配置及項(xiàng)目建立。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-06-06Python基于scipy實(shí)現(xiàn)信號(hào)濾波功能
本文將以實(shí)戰(zhàn)的形式基于scipy模塊使用Python實(shí)現(xiàn)簡(jiǎn)單濾波處理。這篇文章主要介紹了Python基于scipy實(shí)現(xiàn)信號(hào)濾波功能,需要的朋友可以參考下2019-05-05pyecharts調(diào)整圖例與各板塊的位置間距實(shí)例
這篇文章主要介紹了pyecharts調(diào)整圖例與各板塊的位置間距實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05