Python7個爬蟲小案例詳解(附源碼)中篇
本次的7個python爬蟲小案例涉及到了re正則、xpath、beautiful soup、selenium等知識點,非常適合剛?cè)腴Tpython爬蟲的小伙伴參考學習。
前言
關(guān)于Python7個爬蟲小案例的文章分為三篇,本篇為中篇,共兩題,其余兩篇內(nèi)容請關(guān)注!
題目三:
分別使用XPath和Beautiful Soup4兩種方式爬取并保存非異步加載的“豆瓣某排行榜”如https://movie.douban.com/top250的名稱、描述、評分和評價人數(shù)等數(shù)據(jù)
先分析:
首先,來到豆瓣Top250頁面,首先使用Xpath版本的來抓取數(shù)據(jù),先分析下電影列表頁的數(shù)據(jù)結(jié)構(gòu),發(fā)下都在網(wǎng)頁源代碼中,屬于靜態(tài)數(shù)據(jù)

接著我們找到數(shù)據(jù)的規(guī)律,使用xpath提取每一個電影的鏈接及電影名

然后根據(jù)鏈接進入到其詳情頁

分析詳情頁的數(shù)據(jù),發(fā)現(xiàn)也是靜態(tài)數(shù)據(jù),繼續(xù)使用xpath提取數(shù)據(jù)

最后我們將爬取的數(shù)據(jù)進行存儲,這里用csv文件進行存儲

接著是Beautiful Soup4版的,在這里,我們直接在電影列表頁使用bs4中的etree進行數(shù)據(jù)提取

最后,同樣使用csv文件進行數(shù)據(jù)存儲

源代碼即結(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)
# 獲取詳情頁的鏈接列表
href_list = tree.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[1]/a/@href')
# 獲取電影名稱列表
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) # 獲取詳情頁的信息
except:
pass
sleep(1 + random.random()) # 休息
print(f'第{i+1}頁爬取完畢')
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)
# 導演
dir = tree.xpath('//*[@id="info"]/span[1]/span[2]/a/text()')[0]
# 電影類型
type_ = re.findall(r'property="v:genre">(.*?)</span>',html)
type_ = '/'.join(type_)
# 國家
country = re.findall(r'地區(qū):</span> (.*?)<br',html)[0]
# 上映時間
time = tree.xpath('//*[@id="content"]/h1/span[2]/text()')[0]
time = time[1:5]
# 評分
rate = tree.xpath('//*[@id="interest_sectl"]/div[1]/div[2]/strong/text()')[0]
# 評論人數(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)
# 寫入表頭標題
csvwriter.writerow(('電影名稱','導演','電影類型','國家','上映年份','評分','評論人數(shù)'))
for i in range(10): # 爬取10頁
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ā)送請求
page = urllib.request.Request(url, headers=headers)
page = urllib.request.urlopen(page)
contents = page.read()
# 用BeautifulSoup解析網(wǎng)頁
soup = BeautifulSoup(contents, "html.parser")
infofile.write("")
print('爬取豆瓣電影250: \n')
for tag in soup.find_all(attrs={"class": "item"}):
# 爬取序號
num = tag.find('em').get_text()
print(num)
infofile.write(num + "\r\n")
# 電影名稱
name = tag.find_all(attrs={"class": "title"})
zwname = name[0].get_text()
print('[中文名稱]', zwname)
infofile.write("[中文名稱]" + zwname + "\r\n")
# 網(wǎng)頁鏈接
url_movie = tag.find(attrs={"class": "hd"}).a
urls = url_movie.attrs['href']
print('[網(wǎng)頁鏈接]', urls)
infofile.write("[網(wǎng)頁鏈接]" + urls + "\r\n")
# 爬取評分和評論數(shù)
info = tag.find(attrs={"class": "star"}).get_text()
info = info.replace('\n', ' ')
info = info.lstrip()
print('[評分評論]', info)
# 獲取評語
info = tag.find(attrs={"class": "inq"})
if (info): # 避免沒有影評調(diào)用get_text()報錯
content = info.get_text()
print('[影評]', content)
infofile.write(u"[影評]" + content + "\r\n")
print('')
if __name__ == '__main__':
# 存儲文件
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'}
# 翻頁
i = 0
while i < 10:
print('頁碼', (i + 1))
num = i * 25 # 每次顯示25部 URL序號按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()

題目四:
實現(xiàn)某東商城某商品評論數(shù)據(jù)的爬?。ㄔu論數(shù)據(jù)不少于100條,包括評論內(nèi)容、時間和評分)
先分析:

本次選取的某東官網(wǎng)的一款聯(lián)想筆記本電腦,數(shù)據(jù)為動態(tà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}頁爬取完畢')
if __name__ == '__main__':
with open('04.csv','a',encoding='utf-8',newline='')as f:
csvwriter = csv.writer(f)
csvwriter.writerow(('評分','評論時間','評論內(nèi)容'))
for page in range(15):
main(page,f)
sleep(5+random.random())到此這篇關(guān)于Python7個爬蟲小案例詳解(附源碼)中篇的文章就介紹到這了,其他兩個部分的內(nèi)容(上、下篇)請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python7個爬蟲小案例詳解(附源碼)下篇
- Python7個爬蟲小案例詳解(附源碼)上篇
- 利用Python爬蟲爬取金融期貨數(shù)據(jù)的案例分析
- Python爬蟲采集Tripadvisor數(shù)據(jù)案例實現(xiàn)
- Python?Ajax爬蟲案例分享
- Python爬蟲入門案例之爬取去哪兒旅游景點攻略以及可視化分析
- Python爬蟲入門案例之爬取二手房源數(shù)據(jù)
- Python爬蟲入門案例之回車桌面壁紙網(wǎng)美女圖片采集
- Python爬蟲之Scrapy環(huán)境搭建案例教程
- 用Python爬蟲破解滑動驗證碼的案例解析
- python爬蟲系列網(wǎng)絡請求案例詳解
- python爬蟲破解字體加密案例詳解
- python爬蟲線程池案例詳解(梨視頻短視頻爬取)
- python爬蟲scrapy框架的梨視頻案例解析
- python爬蟲利器之requests庫的用法(超全面的爬取網(wǎng)頁案例)
- Python爬蟲實戰(zhàn)案例之爬取喜馬拉雅音頻數(shù)據(jù)詳解
- Python爬蟲Scrapy框架CrawlSpider原理及使用案例
- Python爬蟲之對CSDN榜單進行分析
相關(guān)文章
pyecharts調(diào)整圖例與各板塊的位置間距實例
這篇文章主要介紹了pyecharts調(diào)整圖例與各板塊的位置間距實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05

