爬虫
1.提取本地html中的数据 用Lxml
(1).新建html文件
(2).读取
(3).使用Lxml中的xpath语法进行提取
#调用Lxml
from lxml import html
#读取本地html文件
with open('./index.html','r',encoding='utf-8') as f:
html_data = f.read()
# 解析html文件,获得selector对象,解析树的根结点
selector = html.fromstring(html_data)
# selector中调用xpath方法,提取h1标签中的内容
h1=selector.xpath('/html/body/h1/text()')
print(h1)
'' // " 双斜杠可以表示从任意位置出发
用法: //标签1[@属性=属性值]/标签2[@属性=属性值]..../text()
# 获取文本内容
a = selector.xpath('//div[@id="container"]/a/text()')
print(a)
# 获取属性
link = selector.xpath('//div[@id="container"]/a/@href')
print(link[0])
2.提取远程html中的数据 用requests
# 导入
import requests
url = 'http://www.baidu.com'
# url = 'http://www.taobao.com'
# url = 'https://www.jd.com'
response = requests.get(url)
print(response)
# 获取str类型的响应
print(response.text)
# 获取bytes类型的响应
print(response.content)
# 获取响应头
print(response.headers)
# 获取网页状态码,200成功,404资源找不到,500后台出错
print(response.status_code)
# 没有添加请求头的知乎网站,报400
response = requests.get('https://www.zhihu.com/')
print(response.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"}
response = requests.get('https://www.zhihu.com/',headers=headers)
print(response.status_code)
3.实例1 抓取当当网某一本书的信息
#请求远程端站点
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)
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(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({
'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(10)]
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')
4.实例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
counts={}
# 目标站点地址
def spider_douban():
movie_list=[]
#str.format(),增强了字符串格式化的功能,format 函数可以接受不限个参数,位置可以不按顺序。
url = 'https://movie.douban.com/cinema/later/chongqing/'.format()
#伪装成浏览器
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="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)
# 想看人数
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
})
#按照人数进行排序
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)
# 想看人数
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()
5.关于xpath的用法
https://www.cnblogs.com/lei0213/p/7506130.html