一、提取網(wǎng)頁中數(shù)據(jù)
#爬蟲
#大數(shù)據(jù)
#提取本地html文件
#使用xpath語法進行提取
#使用lxml中的xpath
#使用lxml提取h1中的內(nèi)容
from lxml import html #若報錯找不到指定的模塊,就卸載掉然后再安裝
#提取html文件
with open('./index.html','r',encoding='utf-8') as f:
html_data=f.read()
#print(html_data)
#解析HTML文件,獲取selector對象
selector=html.fromstring(html_data)
#selector中調(diào)用xpath方法
#要獲取標(biāo)簽中的內(nèi)容,末尾要加text()
h1=selector.xpath('/html/body/h1/text()')
print(h1[0])
#//可以代表任意位置出發(fā)
#//標(biāo)簽1[@屬性=屬'性值]/標(biāo)簽2[@屬性=屬性值]container
a=selector.xpath('//div[@class="container"]/a/text()')
print(a[0])
p=selector.xpath('//div[@class="container"]/p/text()')
print(p[0])
#獲取屬性值
link=selector.xpath('//div[@id="container"]/a/@href')
print(link[0])
二、獲取響應(yīng)
#導(dǎo)入
import requests
url='https://www.baidu.com'
response=requests.get(url)
print(response)
#獲取str類型的響應(yīng)
#response常用
print(response.text)
#獲取bytes類型的響應(yīng),下載圖片用到
print(response.content)
#獲取響應(yīng)頭,
print(response.headers)
#獲取狀態(tài)碼:200 404 500
print(response.status_code)
#獲取編碼
print(response.encoding)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>王者榮耀</title>
</head>
<body>
<h1>歡迎來到王者榮耀</h1>
<ul>
<li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/508/508.jpg"> 伽羅</a></li>
<li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/174/174.jpg"> 虞姬</a> </li>
<li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/135/135.jpg" > 項羽</a></li>
<li><a ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/109/109.jpg"> 妲己</a> </li>
</ul>
<ol>
<li>坦克</li>
<li>法師</li>
<li>射手</li>
<li>刺客</li>
</ol>
<div>這是div標(biāo)簽</div>
<div class="container">
<p>被動:伽羅的普工與技能傷害將會有限對于表的護盾效果造成一次等額傷害</p>
<a >點擊跳轉(zhuǎn)</a>
</div>
<div>這是第二個div標(biāo)簽</div>
</body>
</html>

三、對當(dāng)當(dāng)網(wǎng)爬蟲數(shù)據(jù)
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
def spider_dangdang(isbn):
booklist=[]
#目標(biāo)站點地址
url='http://search.dangdang.com/?key={}&act=input'.format(isbn)
#print(url)
#獲取站點str類型的響應(yīng)
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
#將html頁面寫入本地
# with open('./dangdang.html','w',encoding='utf-8') as f:
# f.write(html_data)
#提取目標(biāo)站點的信息
selector=html.fromstring(html_data)
ul_list=selector.xpath('//div[@id="search_nature_rg"]/ul/li')
print('您好,共有{}家店鋪售賣此圖書'.format(len(ul_list)))
#遍歷ul_list
for li in ul_list:
#圖書名稱
title=li.xpath('./a/@title')[0].strip()
print(title)
# 圖書購買鏈接
link = li.xpath('a/@href')[0]
print(link)
#圖書價格
price=li.xpath('./p[@class="price"]/span[@class="search_now_price"]/text()')[0]
price=float(price.replace('¥',''))
print(price)
#圖書賣家名稱
store=li.xpath('./p[@class="search_shangjia"]/a/text()')
if len(store)==0:
store='當(dāng)當(dāng)自營'
else:
store=store[0]
#store ='當(dāng)當(dāng)自營' if len(store)==0 else store[0]
print(store)
#添加每一個商家信息
booklist.append({
'title':title,
'price':price,
'link':link,
'store':store
})
#按照價格進行排序
booklist.sort(key=lambda x:x['price'],reverse=True)
#遍歷booklist
for book in booklist:
print(book)
#展示價格最低的前10家 柱狀圖
#店鋪名稱
top10_store=[booklist[i] for i in range(10)]
# x=[]
# for store in top10_store:
# x.append(store['store'])
x=[x['store'] for x in top10_store]
print(x)
#圖書的價格
y=[x['price'] for x in top10_store]
print(y)
plt.barh(x,y)
plt.show()
#存儲為CSV文件
df=pd.DataFrame(booklist)
df.to_csv('dangdang.csv')
spider_dangdang('9787115428028')
四、練習(xí):對豆瓣網(wǎng)爬蟲
#練習(xí):https://movie.douban.com/cinema/later/chongqing/
#電影名,上映日期,類型,上映國家,想看人數(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
counts={}
# 目標(biāo)站點地址
def spider_douban():
movie_list=[]
url = 'https://movie.douban.com/cinema/later/chongqing/'
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
# 將html頁面寫入本地
# with open('dangdang.html', 'w', encoding='utf-8') as f:
# f.write(html_data)
#提取目標(biāo)站信息
selector = html.fromstring(html_data)
ul_list = selector.xpath('//div[@id="showing-soon"]/div/div')
print('您好,共有{}部電影即將在重慶上映'.format(len(ul_list)))
# 遍歷ul_list
for li in ul_list:
# 電影名稱
title = li.xpath('./h3/a/text()')[0].strip()
print(title)
# 上映日期
date = li.xpath('./ul/li/text()')[0]
print(date)
# 類型
type = li.xpath('./ul/li/text()')[1]
print(type)
# 上映國家
country = li.xpath('./ul/li/text()')[2]
print(country)
# 想看人數(shù)
num = li.xpath('./ul/li/span/text()')[0]
print(num)
num = int(num.replace('人想看', ''))
#添加電影信息
movie_list.append({
'title':title,
'date': date,
'type':type,
'country':country,
'num':num
})
#按照人數(shù)進行排序
movie_list.sort(key=lambda x:x['num'],reverse=True)
#遍歷booklist
for movie in movie_list:
print(movie)
#畫餅圖,把國家提取出來
city=[]
# 提取國家信息
for country in movie_list:
city.append((country['country']))
# 將國家信息匯總
for country in city:
if len(country) <= 1:
continue
else:
counts[country] = counts.get(country, 0) + 1
items = list(counts.items())
print(items)
movie_name=[]
people=[]
for i in range(4):
role, count = items[i]
print(role, count)
movie_name.append(role)
people.append(count)
#繪制即將上映電影國家的占比圖,餅圖
explode = [0.1, 0, 0, 0]
plt.pie(people, explode=explode,labels=movie_name, shadow=True, autopct='%1.1f%%')
plt.axis('equal') # 保證餅狀圖是正圓,否則會有點扁
plt.show()
# 展示最想看的前5家,柱狀圖
# 電影名稱
top5_movie = [movie_list[i] for i in range(5)]
print(top5_movie)
x = [x['title'] for x in top5_movie]
print(x)
# 想看人數(shù)
y = [x['num'] for x in top5_movie]
print(y)
plt.bar(x,y)
#plt.barh(x,y)
plt.show()
存儲成csv文件
df = pd.DataFrame(movie_list)
df.to_csv('douban.csv')
spider_douban()

