爬虫--大数据-- 使用Xpath语法进行解析--使用lxml中的xpath
# 使用lxml提取 h1 标签中的内容
from lxml import html
# 读取html文件
with open('./index.html', 'r', encoding='utf-8') as f:
htm_data = f.read()
# print(htm_data)
# 解析html 文件,获取selector对象
selector = html.fromstring(htm_data)
# selector中调用xpath方法
# 要获取标签中的内容,末尾要添加text()
# /从根节点选取
h1 = selector.xpath('/html/body/h1/text()')
print(h1[0])
# //代表可以从任意位置出发
# //标签1[@属性=属性值】/标签2[@属性=属性值]
a = selector.xpath('//div[@id="container"]/a/text()')
print(a)
# 获取p标签的内容
p = selector.xpath('//div[@id="container"]/p/text()')
print(p[0])
# 获取属性
h = selector.xpath('//div[@id="container"]/a/@href')
print(h[0])
<!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/herolist.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/131/131.jpg" alt=""> 李白</a></li>
<li><a href="https://pvp.qq.com/web201605/herolist.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/106/106.jpg" alt=""> 小乔</a></li>
<li><a href="https://pvp.qq.com/web201605/herolist.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/193/193.jpg" alt=""> 战士</a></li>
</ul>
<ol><!--有序列表 布局-->
<li>刺客</li>
<li>法师</li>
<li>凯</li>
</ol>
<!--div + css 布局-->
<div>第一个div标签</div>
<div id="container">
<P>被动:李白使用普通攻击攻击敌人时,会积累1道剑气,持续3秒;积累4道剑气后进入侠客行状态,增加30点物理攻击力并解除青莲剑歌的封印,持续5秒;攻击建筑不会积累剑气</P>
<a href="http://www.baidu.com/">欢迎来到百度</a>
</div>
<div>第三个div标签</div>
</body>
</html>
Requests
import requests
# Requests
# 导入
import requests
url = 'http://www.baidu.com/'
response = requests.get(url)
print(response)
# 获取str类型的响应
print(response.text)
# 获取bytes类型的响应
print(response.content)
# 获取响应头
print(response.headers)
# 获取状态码
print(response.status_code)
# 获取编码方式
print(response.encoding)
print(response.apparent_encoding)
# 200 Ok 404 500
# 没有添加请求头的知乎网站
resp = requests.get('https://www.zhihu.com/',)
print(resp.status_code)
#使用字典定义请求头
header = {"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('https://www.zhihu.com/',headers=header)
print(resp.status_code)
提取当当网的信息 -图书名称、图书购买链接、图书价格、图书卖家名称—显示价格最低的前10家 柱状图
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):
# 目标站点地址
url = 'http://search.dangdang.com/?key={}&act=input'.format(isbn)
# print(url)
header = {"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=header)
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)))
book_list = []
for li in ul_list:
# 图书名称
title = li.xpath('./a/@title')[0].strip()
print(title)
# 图书购买链接
href = li.xpath('./a/@href')[0]
print(href)
# 图书价格
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()')
store = '当当自营' if len(store) == 0 else store[0]
print(store)
# 添加每一个商家的图书信息
book_list.append({
'name': title,
'link': href,
'price': price,
'store': store
})
# 按照价格进行排序
book_list.sort(key=lambda x: x['price'])
# 遍历book_list
for book in book_list:
print(book)
# 显示价格最低的前10家 柱状图
top10_store = [book_list[i] for i in range(10)]
# x = []
# for store in top10:
# 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')
提取豆瓣电影网站信息—电影名,上映日期,类型,上映国家,想看人数、根据想看人数进行排序、绘制即将上映电影国家的占比图、绘制top5最想看的电影
import requests
from lxml import html
import pandas as pd
import jieba
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def Film():
# 目标站点地址
url = 'https://movie.douban.com/cinema/later/chongqing/'
header = {"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=header)
html_data = resp.text
# 提取目标站的信息
selector = html.fromstring(html_data)
film = selector.xpath('//div[@id="showing-soon"]/div')
print(film)
div_list = []
for film_list in film:
# 电影名
title_list = film_list.xpath('./div/h3/a/text()')[0]
print(title_list)
# 上映时间
time_list = film_list.xpath('./div/ul/li[1]/text()')[0]
print(time_list)
# 电影类型
type_list = film_list.xpath('./div/ul/li[2]/text()')[0]
print(type_list)
# 上映国家
con_list = film_list.xpath('./div/ul/li[3]/text()')[0]
print(con_list)
# 想看人数
number_list = film_list.xpath('./div/ul/li[4]/span/text()')[0]
print(number_list)
# 替换
number_list = int(number_list.replace('人想看',''))
# 添加电影信息
div_list.append({
'title': title_list,
'time': time_list,
'type': type_list,
'con': con_list,
'number': number_list
})
# 按照想看人数排序
div_list.sort(key=lambda x:x['number'], reverse=True )
print(div_list)
# 遍历
for items_list in div_list:
print(items_list)
# 绘制top5最想看的电影占比图
# 提取前五部电影信息
top5_store = [div_list[i] for i in range(5)]
# 提取电影名
x = [x['title'] for x in top5_store]
print(x)
# 提取想看人数
y = [x['number'] for x in top5_store]
print(y)
explode = [0.1, 0, 0, 0, 0]
plt.pie(y, explode=explode, labels=x, shadow=True, autopct='%1.1f%%')
plt.axis('equal')
plt.legend(loc=2)
plt.show()
# 绘制即将上映电影国家的占比图
counts = {}
# 提取所有上映国家
s = [x['con'] for x in div_list]
print(s)
# 统计上映国家与数量
for word in s:
counts[word] = counts.get(word, 0) + 1
print(counts)
# 提取上映国家
name = counts.keys()
print(name)
# 提取数量
number = counts.values()
print(number)
explode1 = [0.1, 0, 0, 0]
plt.pie(number, explode=explode1, labels=name, shadow=True, autopct='%1.1f%%')
plt.axis('equal')
plt.legend(loc=2)
plt.show()
Film()