- 提取本地html中的数据
# 使用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])
- 本地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/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)
对当当网爬虫数据
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=[]
#目标站点地址
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('¥',''))
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)
#添加每一个商家信息
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')