爬虫 【第一章】爬虫基本原理

1、爬虫是什么?css

 

#一、什么是互联网?
    互联网是由网络设备(网线,路由器,交换机,防火墙等等)和一台台计算机链接而成,像一张网同样。

#二、互联网创建的目的?
    互联网的核心价值在于数据的共享/传递:数据是存放于一台台计算机上的,而将计算机互联到一块儿的目的就是为了可以方便彼此之间的数据共享/传递,不然你只能拿U盘去别人的计算机上拷贝数据了。

#三、什么是上网?爬虫要作的是什么?
    咱们所谓的上网即是由用户端计算机发送请求给目标计算机,将目标计算机的数据下载到本地的过程。
    #3.1 只不过,用户获取网络数据的方式是:
      浏览器提交请求->下载网页代码->解析/渲染成页面。

    #3.2 而爬虫程序要作的就是:
      模拟浏览器发送请求->下载网页代码->只提取有用的数据->存放于数据库或文件中
 
    #3.1与3.2的区别在于:
      咱们的爬虫程序只提取网页代码中对咱们有用的数据

#四、总结爬虫
    #4.1 爬虫的比喻:
      若是咱们把互联网比做一张大的蜘蛛网,那一台计算机上的数据即是蜘蛛网上的一个猎物,而爬虫程序就是一只小蜘蛛,沿着蜘蛛网抓取本身想要的猎物/数据

    #4.2 爬虫的定义:
      向网站发起请求,获取资源后分析并提取有用数据的程序 

    #4.3 爬虫的价值:
      互联网中最有价值的即是数据,好比天猫商城的商品信息,链家网的租房信息,雪球网的证券投资信息等等,这些数据都表明了各个行业的真金白银,
能够说,谁掌握了行业内的第一手数据,谁就成了整个行业的主宰,若是把整个互联网的数据比喻为一座宝藏,那咱们的爬虫课程就是来教你们如何来高效地挖掘这些宝藏,
掌握了爬虫技能,你就成了全部互联网信息公司幕后的老板,换言之,它们都在免费为你提供有价值的数据。

2、爬虫的基本流程html

#一、发起请求
使用http库向目标站点发起请求,即发送一个Request
Request包含:请求头、请求体等

#二、获取响应内容
若是服务器能正常响应,则会获得一个Response
Response包含:html,json,图片,视频等

#三、解析内容
解析html数据:正则表达式,第三方解析库如Beautifulsoup,pyquery等
解析json数据:json模块
解析二进制数据:以b的方式写入文件

#四、保存数据
数据库
文

3、请求与响应正则表达式

#http协议:http://www.cnblogs.com/haiyan123/p/7298967.html

#Request:用户将本身的信息经过浏览器(socket client)发送给服务器(socket server)

#Response:服务器接收请求,分析用户发来的请求信息,而后返回数据(返回的数据中可能包含其余连接,如:图片,js,css等)

#ps:浏览器在接收Response后,会解析其内容来显示给用户,而爬虫程序在模拟浏览器发送请求而后接收Response后,是要提取其中的有用数据。

4、Request数据库

#一、请求方式:
    经常使用的请求方式:GET,POST
    其余请求方式:HEAD,PUT,DELETE,OPTHONS

    ps:用浏览器演示get与post的区别,(用登陆演示post)

    post与get请求最终都会拼接成这种形式:k1=xxx&k2=yyy&k3=zzz
    post请求的参数放在请求体内:
        可用浏览器查看,存放于form data内
    get请求的参数直接放在url后

#二、请求url
    url全称统一资源定位符,如一个网页文档,一张图片
    一个视频等均可以用url惟一来肯定

    url编码
    https://www.baidu.com/s?wd=图片
    图片会被编码(看示例代码)


    网页的加载过程是:
    加载一个网页,一般都是先加载document文档,
    在解析document文档的时候,遇到连接,则针对超连接发起下载图片的请求

#三、请求头
    User-agent:告诉它这是浏览器发过来的请求(请求头中若是没有user-agent客户端配置,服务端可能将你当作一个非法用户)务必加上
    host
    cookies:cookie用来保存登陆信息
    Referer:上一次的跳转路径


    通常作爬虫都会加上请求头


#四、请求体
    若是是get方式,请求体没有内容
    若是是post方式,请求体是format data

    ps:
    一、登陆窗口,文件上传等,信息都会被附加到请求体内
    二、登陆,输入错误的用户名密码,而后提交,就能够看到post,正确登陆后页面一般会跳转,没法捕捉到post

import requests
from urllib.parse import urlencode
# 请求方式
kwords = input("请输入关键字:>>").strip()
res = urlencode({"wd":kwords}) # # 请求的url,当你在百度输入中文的时候,你把url拿下来会变成下面的这样格式的url,因此得urlencode一下
url ="https://www.baidu.com/s?"+res #https://www.baidu.com/s?wd=%E5%9B%BE%E7%89%87json

response = requests.get(
# 请求的url,当你在百度输入中文的时候,你把url拿下来会变成下面的这样格式的url
url,
# 请求头
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36",
},
)
with open("a.html","w",encoding="utf-8") as f:
f.write(response.text)
# print(response.status_code)浏览器

示例代码1服务器

kwords = input("请输入关键字:>>").strip()
response = requests.get(
"https://www.baidu.com/s?",
# 请求的url,当你在百度输入中文的时候,你把url拿下来会变成下面的这样格式的url
params={
"wd":kwords,
'pn':20
},
# 请求头
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36",
},
)
with open("b.html","w",encoding="utf-8") as f:
f.write(response.text)
# print(response.status_code)cookie

示例代码二(和上面的结果是同样的)网络

5、Response并发

#一、响应状态
    200:表明成功
    301:表明跳转
    404:文件不存在
    403:权限
    502:服务器错误

#二、Respone header
    Location:跳转
    set-cookie:可能有多个,是来告诉浏览器,把cookie保存下来
    
#三、preview就是网页源代码
    最主要的部分,包含了请求资源的内容
    如网页html,图片
    二进制数据等

6、总结

#一、总结爬虫流程:
    爬取--->解析--->存储

#二、爬虫所需工具:
    请求库:requests,selenium
    解析库:正则,beautifulsoup,pyquery
    存储库:文件,MySQL,Mongodb,Redis

#三、爬虫经常使用框架:
    scrapy

import requests #pip3 install requests
import re
import hashlib
import time

movie_path=r'C:\mp4'

def get_page(url):
try:
response=requests.get(url)
if response.status_code == 200:
return response.text
except Exception:
pass

def parse_index(index_page):
urls=re.findall('class="items".*?href="(.*?)"',index_page,re.S)
for url in urls:
if not url.startswith('http'):
url='http://www.xiaohuar.com'+url
yield url

def parse_detail(detail_page):
l=re.findall('id="media".*?src="(.*?)"',detail_page,re.S)
if l:
movie_url=l[0]
if movie_url.endswith('mp4'):
yield movie_url

def get_movie(url):
try:
response=requests.get(url)
if response.status_code == 200:
m=hashlib.md5()
m.update(str(time.time()).encode('utf-8'))
m.update(url.encode('utf-8'))
filepath='%s\%s.mp4' %(movie_path,m.hexdigest())
with open(filepath,'wb') as f:
f.write(response.content)
print('%s 下载成功' %url)
except Exception:
pass

def main():
base_url='http://www.xiaohuar.com/list-3-{page_num}.html'
for i in range(5):
url=base_url.format(page_num=i)
index_page=get_page(url)
detail_urls=parse_index(index_page)
for detail_url in detail_urls:
detail_page=get_page(detail_url)
movie_urls=parse_detail(detail_page)
for movie_url in movie_urls:
get_movie(movie_url)

if __name__ == '__main__':
main()

爬取校花网视频示例一

import requests #pip3 install requests
import re
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor

pool=ThreadPoolExecutor(50)
movie_path=r'C:\mp4'

def get_page(url):
try:
response=requests.get(url)
if response.status_code == 200:
return response.text
except Exception:
pass

def parse_index(index_page):
index_page=index_page.result()
urls=re.findall('class="items".*?href="(.*?)"',index_page,re.S)
for detail_url in urls:
if not detail_url.startswith('http'):
detail_url='http://www.xiaohuar.com'+detail_url
pool.submit(get_page,detail_url).add_done_callback(parse_detail)

def parse_detail(detail_page):
detail_page=detail_page.result()
l=re.findall('id="media".*?src="(.*?)"',detail_page,re.S)
if l:
movie_url=l[0]
if movie_url.endswith('mp4'):
pool.submit(get_movie,movie_url)

def get_movie(url):
try:
response=requests.get(url)
if response.status_code == 200:
m=hashlib.md5()
m.update(str(time.time()).encode('utf-8'))
m.update(url.encode('utf-8'))
filepath='%s\%s.mp4' %(movie_path,m.hexdigest())
with open(filepath,'wb') as f:
f.write(response.content)
print('%s 下载成功' %url)
except Exception:
pass

def main():
base_url='http://www.xiaohuar.com/list-3-{page_num}.html'
for i in range(5):
url=base_url.format(page_num=i)
pool.submit(get_page,url).add_done_callback(parse_index)

if __name__ == '__main__':
main()

爬取校花网视频示例二(加了并发的)

相关文章
相关标签/搜索