爬虫----大数据
XPath语法和lxml模块
一、 提取本地html中的数据
- 新建html文件
- 读取
- 使用xpath语法进行提取
- 使用 lxml 中的xpath
- 使用lxml提取 h1标签中的内容
.py文件
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中调用xpath方法
# 要获取标签中的内容,末尾要添加text()
h1 = selector.xpath('/html/body/h1/text()')
print(h1[0])
# // 可以代表从任意位置出发、
# //标签1[@属性=属性值]/标签2[@属性=属性值]..../text()
a = selector.xpath('//div[@id="container"]/a/text()')
print(a)
# 获取 p标签的内容
p = selector.xpath('//div[@id="container"]/p/text()')
print(p)
index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>欢迎来到王者荣耀</h1>
<ul>
<li><a href="https://pvp.qq.com/web201605/herodetail/508.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/508/508.jpg" alt="">伽罗</a></li>
<li><img src="" alt="">孙策/li>
<li>铠</li>
<li>虞姬</li>
</ul>
<ol>
<li>坦克</li>
<li>战士</li>
<li>刺客</li>
</ol>
<!--div + css 布局-->
<div>这是div标签</div>
<div id="container">
<p>被动:伽罗的普攻与技能伤害将会优先对目标的护盾效果造成一次等额的伤害</p>
<a href="https://www.baidu.com">点击跳转至百度</a>
</div>
<div>这是第二个div标签</div>
</body>
</html>
运行结果
二、 获取当当网数据
代码如下:
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):
book_list = []
# 目标站点地址
url = 'http://search.dangdang.com/?key={}&act=input'.format(isbn)
# print(url)
# 获取站点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
# 将html页面写入本地
with open('dangdang.html', 'w', encoding='utf-8') as f:
f.write(html_data)
# 提取目标站的信息
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('¥',' '))
price = price.replace('¥', '')
# print(price)
# 图书卖家名称
store = li.xpath('./p[@class="search_shangjia"]/a/text()')
# if len(store) == 0:
# store = '当当自营'
# else:
# store = store[0]
store = '当当自营' if len(store) == 0 else store[0]
# print(store)
# 添加每一个商家的图书信息
book_list.append({
'title':title,
'price':price,
'link':link,
'store':store
})
# 按照价格进行排序
book_list.sort(key=lambda x:x['price'])
# 遍历booklist
for book in book_list:
print(book)
# 展示价格最低的前10家 柱状图
# 店铺的名称
top10_store = [book_list[i] for i in range(12)]
# 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.bar(x, y)
plt.barh(x, y)
plt.show()
# 存储成csv文件
df = pd.DataFrame(book_list)
df.to_csv('dangdang.csv')
spider_dangdang('9787115428028')
运行结果:
三、 练习
提取https://movie.douban.com/cinema/later/chongqing网站以下信息,并且根据信息完成3,4效果
1.电影名,上映日期,类型,上映国家,想看人数
2.根据想看人数进行排序
3.绘制即将上映电影国家的占比图
4.绘制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)
#想看人数
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
})
#根据想看人数进行排序
movie_info_list.sort(key=lambda x : x['want'],reverse=True)
counts={}
# 绘制即将上映电影国家的占比图(饼图)
#计算上映国家的电影片数
for nation in movie_info_list:
counts[nation['nation']] = counts.get(nation['nation'], 0) + 1
#将字典转换为列表
items = list(counts.items())
print(items)
# 取出绘制饼图的数据和标签
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]
#想看人数
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('想看人数(人)')
plt.bar(x, y)
plt.show()