爬蟲
爬蟲(又被稱為網(wǎng)頁蜘蛛,網(wǎng)絡機器人),它是一種按照一定的規(guī)則,自動地抓取互聯(lián)網(wǎng)信息的程序或者腳本。也即它是一段自動抓取互聯(lián)網(wǎng)信息的程序,能從互聯(lián)網(wǎng)上抓取對于我們有價值的信息。面對大數(shù)據(jù)時代,互聯(lián)網(wǎng)中浩瀚的數(shù)據(jù),如何從中抓取信息,并篩選出有價值的信息呢?答案就是Python爬蟲,Python是最適合開發(fā)爬蟲的程序語言,一方面有優(yōu)先的開發(fā)包,另一方面它又擅長對數(shù)據(jù)進行處理。
1.本地提取
1.1新建html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>歡迎來到王者榮耀</h1>
<ul>
<li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/190/190.jpg" alt="">諸葛亮</a></li>
<li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/112/112.jpg" alt="">魯班七號</a></li>
<li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/169/169.jpg" alt="">后裔</a></li>
<li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/174/174.jpg" alt="">虞姬</a></li>
</ul>
<ol>
<li>坦克</li>
<li>戰(zhàn)士</li>
<li>射手</li>
<li>刺客</li>
<li>法師</li>
<li>輔助</li>
</ol>
<!--div+css布局-->
<div id="car">
<a >點擊跳轉(zhuǎn)至諸葛亮的英雄主頁</a>
<p>被動</p>
</div>
</body>
</html>
1.2讀取
1.3使用xpath語法進行提取
使用lxml提取h1標簽中的內(nèi)容
from lxml import html
with open('./index.html','r',encoding='utf-8') as f:
html_data=f.read()
解析html文件,使用selector對象
selector=html.fromstring(html_data)
selector中調(diào)用xpath方法
要獲取標簽中的內(nèi)容,末尾要添加text()
h1=selector.xpath('/html/body/h1/text()')
print(h1[0])
使用//,從任意位置出發(fā)
格式: //標簽1[@屬性=屬性值]/[@屬性=屬性值].../text()
a=selector.xpath('//div[@id="car"]/a/text()')
print(a[0])
#獲取p標簽的內(nèi)容
p = selector.xpath('//div[@id="car"]/p/text()')
print(p[0])
#獲取屬性
link=selector.xpath('//div[@id="car"]/a/@href')
print(link[0])
2.提取百度(https://www.baidu.com)網(wǎng)址信息
導入及提取
import requests
url='https://www.baidu.com'
response=requests.get(url)
print(response)
獲取str類型的響應
print(response.text)
獲取bytes類型的響應
print(response.content)
獲取響應頭
print(response.headers)
獲取狀態(tài)碼
print(response.status_code)
獲取編碼方式
print(response.encoding)
沒有添加請求頭
req=requests.get('https://www.zhihu.com/')
print(req.status_code)
會出現(xiàn)400錯誤
在使用python爬蟲爬取數(shù)據(jù)的時候,經(jīng)常會遇到一些網(wǎng)站的反爬蟲措施,一般就是針對于headers中的User-Agent,如果沒有對headers進行設置,User-Agent會聲明自己是python腳本,而如果網(wǎng)站有反爬蟲的想法的話,必然會拒絕這樣的連接。而修改headers可以將自己的爬蟲腳本偽裝成瀏覽器的正常訪問,來避免這一問題。
添加,使用字典定義請求頭
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"}
req=requests.get('https://www.zhihu.com/', headers=headers)
print(req.status_code)

使用爬蟲提取當當?shù)男畔?/h1>
利用爬蟲提取當當網(wǎng)上書號為9787115428028的圖書信息,并將前10價格最便宜的店鋪信息繪制成柱狀圖
1導入
.import requests
from lxml import html
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
2.自定義一個函數(shù),isbn為書號,函數(shù)調(diào)用時傳值,所有操作都在函數(shù)內(nèi)部完成
def spider_dangdang(isbn):
3.獲取站點str的響應,book_list列表中存放圖書的信息(書名,店鋪,價格,購買鏈接),后面會用到
book_list=[]
#目標站點地址
url='http://search.dangdang.com/?key={}&act=input'.format(isbn)
#獲取站點str類型的響應
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"}
resp=requests.get(url,headers=headers)
html_data=resp.text
4.提取目標站點的信息
selector=html .fromstring(html_data)
ul_list=selector.xpath('//div[@id="search_nature_rg"]/ul/li')
print('你好,共有{}家店鋪售賣此書'.format(len(ul_list)))
for li in ul_list:
# 圖書名稱
title=li.xpath('./a/@title')[0].strip()
# 圖書價格
price=li.xpath('./p[@ class="price"]/span[@class="search_now_price"]/text()')[0]
price = float(price.replace('¥',''))
# print(price)
#圖書購買鏈接
link=li.xpath('./a/@href')[0]
#圖書賣家信息
store = li.xpath('./p[@class="search_shangjia"]/a/text()')
store = '當當自營' if len(store) == 0 else store[0]
#添加每個商家的圖書信息
book_list.append({
'title':title,
'price':price,
'link':link,
'store':store
})
5.按照價格排序
book_list.sort(key=lambda x : x['price'])
for book in book_list:
print(book)
6.展示價格最低的前10家 柱狀圖
#店鋪
x = [book_list[i]['store'] for i in range(10)]
# 圖書的價格
y = [book_list[i]['price'] for i in range(10)]
plt.barh(x, y)
plt.show()
7.存儲為CSV文件
df = pd.DataFrame(book_list)
df.to_csv('dangdang.csv')
8.調(diào)用函數(shù)
spider_dangdang('9787115428028')
練習
提取https://movie.douban.com/cinema/later/chongqing網(wǎng)站以下信息,并且根據(jù)信息完成3,4效果
-電影名,上映日期,類型,上映國家,想看人數(shù)
-根據(jù)想看人數(shù)進行排序
-繪制即將上映電影國家的占比圖
-繪制top5最想看的電影
完整代碼:
import requests
from lxml import html
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
url='https://movie.douban.com/cinema/later/chongqing/'
resp = requests.get(url)
#獲取站點str類型的
html_data=resp.text
# 提取目標站點的信息
selector = html.fromstring(html_data)
movie_info=selector.xpath('//div[@id="showing-soon"]/div')
#print(html_data)
print('你好,共有{}電影即將上映'.format(len(movie_info)))
movie_info_list=[]
for movie in movie_info:
#電影名
movie_name=movie.xpath('./div/h3/a/text()')[0]
# print(movie_name)
#上映日期
movie_date=movie.xpath('./div/ul/li[1]/text()')[0]
# print(movie_date)
#電影類型
movie_type=movie.xpath('./div/ul/li[2]/text()')[0]
movie_type=str(movie_type)
movie_type=movie_type.split(' / ')
# print(type(movie_type))
#print(movie_type)
#上映國家
movie_nation=movie.xpath('./div/ul/li[3]/text()')[0]
# print(movie_nation)
#想看人數(shù)
movie_want = movie.xpath('./div/ul/li[4]/span/text()')[0]
movie_want=int(movie_want.replace('人想看',''))
# print(movie_want)
#添加信息到列表
movie_info_list.append({
'name':movie_name,
'date':movie_date,
'type':movie_type,
'nation':movie_nation,
'want':movie_want
})
#根據(jù)想看人數(shù)進行排序
movie_info_list.sort(key=lambda x : x['want'],reverse=True)
counts={}
# 繪制即將上映電影國家的占比圖(餅圖)
#計算上映國家的電影片數(shù)
for nation in movie_info_list:
counts[nation['nation']] = counts.get(nation['nation'], 0) + 1
#將字典轉(zhuǎn)換為列表
items = list(counts.items())
print(items)
# 取出繪制餅圖的數(shù)據(jù)和標簽
co=[]
lables=[]
for i in range(len(items)):
role, count = items[i]
co.append(count)
lables.append(role)
explode = [0.1, 0, 0, 0]
plt.pie(co, shadow=True,explode=explode, labels=lables, autopct = '%1.1f%%')
plt.legend(loc=2)
plt.axis('equal')
plt.show()
#繪制top5最想看的電影(柱狀圖)
#電影名稱
x = [movie_info_list[i]['name'] for i in range(5)]
# top5 = [movie_info_list[i] for i in range(5)]
# x = [x['name'] for x in top5]
#想看人數(shù)
y = [movie_info_list[i]['want'] for i in range(5)]
# y = [y['want'] for y in top5]
print(x)
print(y)
plt.xlabel('電影名稱')
plt.ylabel('想看人數(shù)(人)')
plt.bar(x, y)
plt.show()