爬虫
1. 爬虫练习
- 本地新建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/190.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/190/190.jpg" alt="">诸葛亮</a></li>
<li><a href="https://pvp.qq.com/web201605/herodetail/112.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/112/112.jpg" alt="">鲁班七号</a></li>
<li><a href="https://pvp.qq.com/web201605/herodetail/169.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/169/169.jpg" alt="">后裔</a></li>
<li><a href="https://pvp.qq.com/web201605/herodetail/174.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/174/174.jpg" alt="">虞姬</a></li>
</ul>
<ol>
<li>坦克</li>
<li>战士</li>
<li>射手</li>
<li>刺客</li>
<li>法师</li>
<li>辅助</li>
</ol>
<!--div+css布局-->
<div id="car">
<a href="https://pvp.qq.com/web201605/herodetail/190.shtml">点击跳转至诸葛亮的英雄主页</a>
<p>被动</p>
</div>
</body>
</html>
- 读取
- 使用xpath语法进行提取
使用lxml提取h1标签中的内容
from lxml import html
with open('./index.html','r',encoding='utf-8') as f:
html_data=f.read()
selector=html.fromstring(html_data)
h1=selector.xpath('/html/body/h1/text()')
print(h1[0])
a=selector.xpath('//div[@id="car"]/a/text()')
print(a[0])
#获取p标签的内容
p = selector.xpath('//div[@id="car"]/p/text()')
print(p[0])
#获取属性
link=selector.xpath('//div[@id="car"]/a/@href')
print(link[0])
- 提取百度网址信息
import requests
url='https://www.baidu.com'
response=requests.get(url)
print(response)
print(response.text)
print(response.content)
print(response.headers)
print(response.status_code)
print(response.encoding)
req=requests.get('https://www.zhihu.com/')
print(req.status_code)
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)
2. 提取当当网信息
.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)
#获取站点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
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
})
book_list.sort(key=lambda x : x['price'])
for book in book_list:
print(book)
#店铺
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()
3. 提取豆瓣网信息
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()
效果图