一、爬虫

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

互联网的核心价值在于数据的共享/传递:数据是存放于一台台计算机上的,而将计算机互联到一起的目的就是为了能够方便彼此之间的数据共享/传递,否则就只能拿U盘去拷贝数据了。

互联网中最有价值的便是数据,爬虫模拟浏览器发送请求->下载网页代码->只提取有用的数据->存放于数据库或文件中,就得到了我们需要的数据了

爬虫是一种向网站发起请求,获取资源后分析并提取有用数据的程序。


二、爬虫流程

1、基本流程介绍

发送请求-----> 获取响应内容----->解析内容 ----->保存数据

  1. #1、发起请求
  2. 使用http库向目标站点发起请求,即发送一个Request
  3. Request包含:请求头、请求体等
  4. #2、获取响应内容
  5. 如果服务器能正常响应,则会得到一个Response
  6. Response包含:html,json,图片,视频等
  7. #3、解析内容
  8. 解析html数据:正则表达式,第三方解析库如Beautifulsoup,pyquery等
  9. 解析json数据:json模块
  10. 解析二进制数据:以b的方式写入文件
  11. #4、保存数据
  12. 数据库
  13. 文件


2、Request

常用的请求方式:GET,POST

其他请求方式:HEAD,PUT,DELETE,OPTHONS


  1. >>> import requests
  2. >>> r = requests.get('https://api.github.com/events')
  3. >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
  4. >>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})
  5. >>> r = requests.delete('http://httpbin.org/delete')
  6. >>> r = requests.head('http://httpbin.org/get')
  7. >>> r = requests.options('http://httpbin.org/get')


百度搜索内容爬取页面:

  1. import requests
  2. response=requests.get("https://www.baidu.com/s",
  3.                       params={"wd":"美女","a":1},
  4.                       headers={
  5. "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"
  6.                       })                #模拟在百度搜索美女的第一页内容,wd后面跟输入的搜索内容  #自己定制headers,解决网站的反爬虫功能
  7. print(response.status_code)
  8. print(response.text)
  9. with open("bd.html","w",encoding="utf8"as f:
  10.     f.write(response.text)                        #下载的页面写进bd.html文件,文件用浏览器打开发现和百度页面一样


3、Response

# 1、响应状态

200:代表成功

301:代表跳转

404:文件不存在

403:权限

502:服务器错误


# 2、Respone header

Location:跳转

set - cookie:可能有多个,是来告诉浏览器,把cookie保存下来


# 3、preview就是网页源代码

最主要的部分,包含了请求资源的内容

如网页html,图片,二进制数据等


# 4、response属性

  1. import requests
  2. respone=requests.get('http://www.jianshu.com')
  3. # respone属性
  4. print(respone.text)                     # 获取响应文本
  5. print(respone.content)                 #获取网页上的二进制图片、视频
  6. print(respone.status_code)               #响应状态码
  7. print(respone.headers)                   #响应头
  8. print(respone.cookies)                   #获取cookies信息
  9. print(respone.cookies.get_dict())
  10. print(respone.cookies.items())
  11. print(respone.url)
  12. print(respone.history)                 #获取history信息(页面经过重定向等方式,不是一次返回的页面)
  13. print(respone.encoding)                #响应字符编码
  14. #关闭:response.close()
  15. from contextlib import closing
  16. with closing(requests.get('xxx',stream=True)) as response:
  17.     for line in response.iter_content():
  18.     pass


#5、获取大文件

  1. #stream参数:一点一点的取,对于特别大的资源,一下子写到文件中是不合理的
  2. import requests
  3. response=requests.get('https://gss3.baidu.com/6LZ0ej3k1Qd3ote6lo7D0j9wehsv/tieba-smallvideo-transcode/1767502_56ec685f9c7ec542eeaf6eac93a65dc7_6fe25cd1347c_3.mp4',
  4.                       stream=True)
  5. with open('b.mp4','wb'as f:
  6.     for line in response.iter_content():           # 获取二进制流(iter_content)
  7.         f.write(line)


三、爬取校花网视频(加了并发的)

  1. import requests         #安装模块 pip3 install requests
  2. import re
  3. import hashlib
  4. import time
  5. from concurrent.futures import ThreadPoolExecutor
  6. pool=ThreadPoolExecutor(50)
  7. movie_path=r'C:\mp4'
  8. def get_page(url):
  9.     try:
  10.         response=requests.get(url)
  11.         if response.status_code == 200:
  12.             return response.text
  13.     except Exception:
  14.         pass
  15.         
  16. def parse_index(index_page):
  17.     index_page=index_page.result()
  18.     urls=re.findall('class="items".*?href="(.*?)"',index_page,re.S)       #找到所有属性类为items的标签的链接地址,re.S表示前面的.*?代表所有字符
  19.     for detail_url in urls:
  20.         ret = re.search('<video.*?source src="(?P<path>.*?)"', res.text, re.S)   #找到所有video标签的链接地址
  21.         detail_url = ret.group("path")
  22.         res = requests.get(detail_url)
  23.         if not detail_url.startswith('http'):
  24.             detail_url='http://www.xiaohuar.com'+detail_url
  25.         pool.submit(get_page,detail_url).add_done_callback(parse_detail)
  26.         
  27. def parse_detail(detail_page):
  28.     detail_page=detail_page.result()
  29.     l=re.findall('id="media".*?src="(.*?)"',detail_page,re.S)
  30.     if l:
  31.         movie_url=l[0]
  32.         if movie_url.endswith('mp4'):
  33.             pool.submit(get_movie,movie_url)
  34.             
  35. def get_movie(url):
  36.     try:
  37.         response=requests.get(url)
  38.         if response.status_code == 200:
  39.             m=hashlib.md5()
  40.             m.update(str(time.time()).encode('utf-8'))
  41.             m.update(url.encode('utf-8'))
  42.             filepath='%s\%s.mp4' %(movie_path,m.hexdigest())
  43.             with open(filepath,'wb'as f:                        #视频文件,wb保存
  44.                 f.write(response.content)
  45.                 print('%s 下载成功' %url)
  46.     except Exception:
  47.         pass
  48.         
  49. def main():
  50.     base_url='http://www.xiaohuar.com/list-3-{page_num}.html'
  51.     for i in range(5):
  52.         url=base_url.format(page_num=i)
  53.         pool.submit(get_page,url).add_done_callback(parse_index)
  54.         
  55. if __name__ == '__main__':
  56.     main()


四、爬虫模拟登陆github网站

  1. import requests
  2. import re
  3. # 第三次请求,登录成功之后
  4.     #- 请求之前自己先登录一下,看一下有没有referer
  5.     #- 请求新的url,进行其他操作
  6.     #- 查看用户名在不在里面
  7.     
  8. #第一次请求GET请求
  9. response1 = requests.get(
  10.     "https://github.com/login",
  11.     headers = {
  12.         "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",
  13.     },
  14. )
  15. authenticity_token = re.findall('name="authenticity_token".*?value="(.*?)"',response1.text,re.S)
  16. r1_cookies =  response1.cookies.get_dict()                   #获取到的cookie
  17. #第二次请求POST请求
  18. response2 = requests.post(
  19.     "https://github.com/session",
  20.     headers = {
  21.         "Referer""https://github.com/",
  22.         "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",
  23.     },
  24.     data={
  25.             "commit":"Sign in",
  26.             "utf8":"✓",
  27.             "authenticity_token":authenticity_token,
  28.             "login":"zzzzzzzz",
  29.             "password":"xxxx",
  30. zhy..azjash1234
  31.     },
  32.     cookies = r1_cookies
  33. )
  34. print(response2.status_code)
  35. print(response2.history)  #跳转的历史状态码
  36. #第三次请求,登录成功之后,访问其他页面
  37. r2_cookies = response2.cookies.get_dict()           #拿上cookie,表示登陆状态,开始访问页面
  38. response3 = requests.get(
  39.     "https://github.com/settings/emails",
  40.     headers = {
  41.         "Referer""https://github.com/",
  42.         "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",
  43.     },
  44.     cookies = r2_cookies,
  45. )
  46. print(response3.text)
  47. print("zzzzzzzz" in response3.text)             #返回True说明就成功了


五、高级用法

1、SSL Cert Verification

  1. import requests
  2. respone=requests.get('https://www.12306.cn',
  3.                      cert=('/path/server.crt','/path/key'))
  4. print(respone.status_code)


2、使用代理

  1. #官网链接: http://docs.python-requests.org/en/master/user/advanced/#proxies
  2. #代理设置:先发送请求给代理,然后由代理帮忙发送(封ip是常见的事情)
  3. import requests
  4. proxies={
  5.     'http':'http://egon:123@localhost:9743',#带用户名密码的代理,@符号前是用户名与密码
  6.     'http':'http://localhost:9743',
  7.     'https':'https://localhost:9743',
  8. }
  9. respone=requests.get('https://www.12306.cn',proxies=proxies)
  10. print(respone.status_code)
  11. #支持socks代理,安装:pip install requests[socks]
  12. import requests
  13. proxies = {
  14.     'http''socks5://user:pass@host:port',
  15.     'https''socks5://user:pass@host:port'
  16. }
  17. respone=requests.get('https://www.12306.cn',proxies=proxies)
  18. print(respone.status_code)


3、超时设置

  1. #两种超时:float or tuple
  2. #timeout=0.1 #代表接收数据的超时时间
  3. #timeout=(0.1,0.2)#0.1代表链接超时  0.2代表接收数据的超时时间
  4. import requests
  5. respone=requests.get('https://www.baidu.com', timeout=0.0001)


4、认证设置

  1. #官网链接:http://docs.python-requests.org/en/master/user/authentication/
  2. #认证设置:登陆网站是,弹出一个框,要求你输入用户名密码(与alter很类似),此时是无法获取html的
  3. # 但本质原理是拼接成请求头发送
  4. #         r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
  5. #看一看默认的加密方式吧,通常网站都不会用默认的加密设置
  6. import requests
  7. from requests.auth import HTTPBasicAuth
  8. r=requests.get('xxx',auth=HTTPBasicAuth('user','password'))
  9. print(r.status_code)
  10. #HTTPBasicAuth可以简写为如下格式
  11. import requests
  12. r=requests.get('xxx',auth=('user','password'))
  13. print(r.status_code)


5、异常处理

  1. import requests
  2. from requests.exceptions import * #可以查看requests.exceptions获取异常类型
  3. try:
  4.     r=requests.get('http://www.baidu.com',timeout=0.00001)
  5. except ReadTimeout:
  6.     print('===:')
  7. # except ConnectionError:
  8. #     print('-----网络不通')
  9. # except Timeout:
  10. #     print('aaaaa')
  11. except RequestException:
  12.     print('Error')


6、上传文件

  1. import requests
  2. files={'file':open('a.jpg','rb')}
  3. respone=requests.post('http://httpbin.org/post',files=files)
  4. print(respone.status_code)