1.爬虫基础
1.1获取网址
url='https://www.baidu.com'
response=requests.get(url)
1.2获取str类型的响应
print(response.text)
1.3获取bytes类型的响应
print(response.content)
1.4获取响应头
print(response.headers)
1.5获取状态码
print(response.status_code)
1.6响应头用以伪装成浏览器
#没有添加响应头
# resp=requests.get('https://www.zhihu.com/')
# print(resp.status_code)
#运行返回400
#使用字典定义请求头
headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
resp=requests.get('https://pvp.qq.com/')
print(resp.status_code)
#运行返回200
2.静态网页爬虫
2.1导入lxml库
from lxml import html
2.2打开并读取本地html文件
with open('./index.html','r',encoding='utf-8') as f:
html_data=f.read()
print(html_data)
2.3解析html文件,获取selector对象
selector =html.fromstring(html_data)
#要获取标签内容,末尾要添加text()
h1=selector.xpath('/html/body/h1/text()')
print(h1[0])
2.4//表示可以代表任意位置出发
#//标签1[@属性=属性值]/标签2[@属性=属性值]..../text()
a=selector.xpath('//div[@id="container"]/a/text()')
print(a)
3.动态网页爬虫(当当网和电影网)
3.1导入库
import requests
from lxml import html
import pandas as pd
from matplotlib import pyplot as plt
3.2设置响应头和url
浏览器中按f12,点击network,刷新界面,下面的name中随意选取查看右边信息的User-Agent
def spider_dangdang(isbn):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
#装图书信息的list
book_list = []
#目标站点地址
url='http://search.dangdang.com/?key={}&act=input'.format(isbn)
3.3获取站点str类型的响应
resp=requests.get(url,headers=headers)
html_data=resp.text
3.4提取目标站所有图书信息
selector=html.fromstring(html_data)
ul_list=selector.xpath('//div[@id="search_nature_rg"]/ul/li')
print('共有{}家店铺售卖此书'.format(len(ul_list)))
3.5遍历信息获取想要的数据
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='当当自营'
store='当当自营' if len(store) ==0 else store[0]
#添加每个商家的图书信息
book_list.append({
'title':title,
'link':link,
'price':price,
'store':store
})
#排序
book_list.sort(key=lambda x:x['price'])
3.6获取销量最高的10家绘制柱状图
#展示价格最低的10家 柱状图
top10_store=[book_list[i] for i in range(10)]
# x=[]
# for stroe in top10_store:
# x.append(store['store'])
x=[x['store'] for x in top10_store]
y=[x['price'] for x in top10_store]
plt.barh(x,y)
plt.show()
3.7存储成csv文件
df=pd.DataFrame(book_list)
df.to_csv('dangdang.csv')
#以上步骤均是在函数spider_dangdang中执行
3.8调用函数
#要查询的图书的编号9787115428028
spider_dangdang('9787115428028')
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
counts={}
# 目标站点地址
def spider_douban():
movie_list=[]
url = 'https://movie.douban.com/cinema/later/chongqing/'
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.电影网爬虫
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_film():
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
film_list = []
#目标站点地址
url='https://movie.douban.com/cinema/later/chongqing/'
#获取站点str类型的响应
resp=requests.get(url,headers=headers)
html_data=resp.text
#提取目标站信息
selector=html.fromstring(html_data)
ul_list=selector.xpath('//div[@id="showing-soon"]/div')
print('您好,共有{}部电影'.format(len(ul_list)))
#遍历 ul_list
for div in ul_list:
#电影名
title=div.xpath('./div/h3/a/text()')[0]
print(title)
#上映日期
date=div.xpath('./div/ul/li/text()')[0]
print(date)
#类型
style=div.xpath('./div/ul/li/text()')[1]
print(style)
#上映国家
state =div.xpath('./div/ul/li/text()')[2]
print(state)
#想看人数
want_people = div.xpath('./div/ul/li[@class="dt last"]/span/text()')[0]
want_people = int(want_people.replace('人想看', ''))
print(want_people)
#添加每个电影的图书信息
film_list.append({
'title':title,
'date':date,
'style':style,
'state':state,
'want_people':want_people
})
#排序
film_list.sort(key=lambda x:x['want_people'])
#展示价格最低的10家 柱状图
top5_film=[film_list[i] for i in range(5)]
x=[x['title'] for x in top5_film]
y=[x['want_people'] for x in top5_film]
plt.barh(x,y)
plt.show()
# 调用函数
spider_film()