数据解析,懒加载,代理ip

  在前面的requests流程中,还缺乏了一步重要的流程,就是在持久化存储以前须要进行制定的数据解析.由于在大多数状况下,咱们都会使用聚焦爬虫,也就是爬取页面中的指定部分数据值,而不是整个页面的数据.php

  因此,数据爬取的流程应该是 : 

    1). 指定urlhtml

    2). 基于requests模块发起请求java

    3). 获取响应中的数据python

    4). 数据解析linux

    5). 进行持久化存储c++

 一 . 正则解析

    1 .  经常使用正则表达式回顾 : 
 #单字符:
        .     :   除换行之外全部字符
        []   :  [aoe] [a-w] 匹配集合中任意一个字符
        \d   :  数字  [0-9]
        \D  :   非数字
        \w  :  数字、字母、下划线、中文
        \W  :   非\w
        \s   :  全部的空白字符包,括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
        \S   :    非空白
 # 数量修饰:
        *   :   任意屡次  >=0
        +   :   至少1次   >=1
        ?   :   无关紧要  0次或者1次
       {m}   :   固定m次 hello{3,}
       {m,}   :  至少m次
       {m,n}  : m-n次
 #边界:
        $    :  以某某结尾 
        ^   :  以某某开头
 #分组:
        (ab)  
    贪婪模式 : .*
    非贪婪(惰性)模式 : .*?

    re.I   :    忽略大小写
    re.M   : 多行匹配
    re.S   : 单行匹配

    re.sub(正则表达式, 替换内容, 字符串)

   2 . 回顾练习 : 正则表达式

import re
#提取出python
key="javapythonc++php"
re.findall('python',key)[0]

#####################################################################

#提取出hello world
key="<html><h1>hello world<h1></html>"
re.findall('<h1>(.*)<h1>',key)[0]

#####################################################################

#提取170
string = '我喜欢身高为170的女孩'
re.findall('\d+',string)

#####################################################################
#提取出http://和https://
key='http://www.baidu.com and https://boob.com'
re.findall('https?://',key)
#####################################################################

#提取出hello
key='lalala<hTml>hello</HtMl>hahah' #输出<hTml>hello</HtMl>
re.findall('<[Hh][Tt][mM][lL]>(.*)</[Hh][Tt][mM][lL]>',key)

#####################################################################

#提取出hit. 
key='bobo@hit.edu.com'#想要匹配到hit.
re.findall('h.*?\.',key)

#####################################################################

#匹配sas和saas
key='saas and sas and saaas'
re.findall('sa{1,2}s',key)

#####################################################################

#匹配出i开头的行
string = '''fall in love with you
i love you very much
i love she
i love her'''

re.findall('^.*',string,re.M)

#####################################################################

#匹配所有行
string1 = """<div>静夜思
窗前明月光
疑是地上霜
举头望明月
低头思故乡
</div>"""

re.findall('.*',string1,re.S)
正则回顾练习

   3 . 使用正则爬取'糗事百科指定的页面图片',并保持到指定文件中windows

import requests
import re
import urllib    # 保存文件的 , 至关于 with open
import os

url = 'https://www.qiushibaike.com/pic/page/%d/?s=5170552'
# page = 1
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
}
# 建立文件夹(若是没有就建立)
if not os.path.exists('./qiutu'):
    os.mkdir('./qiutu')
    
# 指定起始页码和结束页码
start_page = int(input('enter a start pageNum:'))
end_page = int(input('enter a end pageNum:'))
# 循环解析并下载指定页码的图片数据
for page in range(start_page,end_page+1):
    # 第几页
    new_url = format(url%page)
    # 获取页面源代码
    page_text = requests.get(url=new_url,headers=headers).text
    #正则解析图片的标签
    img_url_list = re.findall('<div class="thumb">.*?<img src="(.*?)" alt=.*?</div>',page_text,re.S)
    # 循环下载该页码的图片数据
    for url in img_url_list:
        url = 'https:'+url
        imgName = url.split('/')[-1]
        imgPath = 'qiutu/'+imgName
       # 能够直接写入文件夹中
        urllib.request.urlretrieve(url=url,filename=imgPath)
        #print(imgPath,'下载成功!')
        
print('over!!!')

 

二 . Xpath 解析  

   1 .  测试页面数据 : 
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>测试bs4</title>
</head>
<body>
    <div>
        <p>百里守约</p>
    </div>
    <div class="song">
        <p>李清照</p>
        <p>王安石</p>
        <p>苏轼</p>
        <p>柳宗元</p>
        <a href="http://www.song.com/" title="赵匡胤" target="_self">
            <span>this is span</span>
        宋朝是最强大的王朝,不是军队的强大,而是经济很强大,国民都颇有钱</a>
        <a href="" class="du">总为浮云能蔽日,长安不见令人愁</a>
        <img src="http://www.baidu.com/meinv.jpg" alt="" />
    </div>
    <div class="tang">
        <ul>
            <li><a href="http://www.baidu.com" title="qing">清明时节雨纷纷,路上行人欲断魂,借问酒家何处有,牧童遥指杏花村</a></li>
            <li><a href="http://www.163.com" title="qin">秦时明月汉时关,万里长征人未还,但使龙城飞将在,不教胡马度阴山</a></li>
            <li><a href="http://www.126.com" alt="qi">岐王宅里寻常见,崔九堂前几度闻,正是江南好风景,落花时节又逢君</a></li>
            <li><a href="http://www.sina.com" class="du">杜甫</a></li>
            <li><a href="http://www.dudu.com" class="du">杜牧</a></li>
            <li><b>杜小月</b></li>
            <li><i>度蜜月</i></li>
            <li><a href="http://www.haha.com" id="feng">凤凰台上凤凰游,凤去台空江自流,吴宫花草埋幽径,晋代衣冠成古丘</a></li>
        </ul>
    </div>
</body>
</html>

  2 . 经常使用的xpath表达式 : 浏览器

#属性定位:
      #找到class属性值为song的div标签
      //div[@class="song"] 
#层级&索引定位:
    #找到class属性值为tang的div的直系子标签ul下的第二个子标签li下的#直系子标签a
      //div[@class="tang"]/ul/li[2]/a
#逻辑运算:
    #找到href属性值为空且class属性值为du的a标签
    //a[@href="" and @class="du"]
#模糊匹配:
    //div[contains(@class, "ng")]
    //div[starts-with(@class, "ta")]
#取文本:
    # / 表示获取某个标签下的文本内容
    # // 表示获取某个标签下的文本内容和全部子标签下的文本内容
    //div[@class="song"]/p[1]/text()
    //div[@class="tang"]//text()
#取属性:
    //div[@class="tang"]//li[2]/a/@href
    3 .  代码中使用xpath表达式进行数据解析 : 
#1.下载:
          pip install lxml
2#.导包:
          from lxml import etree

#3.将html文档或者xml文档转换成一个etree对象,而后调用对象中的方法查找指定的节点

  #3.1 本地文件:tree = etree.parse(文件名)
                tree.xpath("xpath表达式")

  #3.2 网络数据:tree = etree.HTML(网页内容字符串)
                tree.xpath("xpath表达式")

   安装xpath插件在浏览器对xpath表达式进行验证 : 能够直接在插件中执行 xpath表达式 服务器

    将xpath插件拖动到谷歌浏览器的扩展程序中(更多工具->扩展程序),安装成功

    插件下载  ---> xpath插件.zip

      启动和关闭插件 : Ctrl + shift + x 

  5 . 案例演示 

    ● 爬取 '好段子'网站中的内容和标题 

from lxml import etree
import requests

url='http://www.haoduanzi.com/category-10_2.html'
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
    }
url_content=requests.get(url,headers=headers).text
#使用xpath对url_conten进行解析
#使用xpath解析从网络上获取的数据
tree=etree.HTML(url_content)
#解析获取当页全部段子的标题
title_list=tree.xpath('//div[@class="log cate10 auth1"]/h3/a/text()')

ele_div_list=tree.xpath('//div[@class="log cate10 auth1"]')

text_list=[] #最终会存储12个段子的文本内容
for ele in ele_div_list:
    #段子的文本内容(是存放在list列表中)
    text_list=ele.xpath('./div[@class="cont"]//text()')
    #list列表中的文本内容所有提取到一个字符串中
    text_str=str(text_list)
    #字符串形式的文本内容防止到all_text列表中
    text_list.append(text_str)
print(title_list)
print(text_list)
    ●  爬取 煎蛋网 中图片数据 : (图片地址加密的 *********
import requests
from lxml import etree
from fake_useragent import UserAgent
import base64
import urllib.request
url = 'http://jandan.net/ooxx'
ua = UserAgent(verify_ssl=False,use_cache_server=False).random
headers = {
    'User-Agent':ua
}
page_text = requests.get(url=url,headers=headers).text

#查看页面源码:发现全部图片的src值都是同样的。
#简单观察会发现每张图片加载都是经过jandan_load_img(this)这个js函数实现的。
#在该函数后面还有一个class值为img-hash的标签,里面存储的是一组hash值,该值就是加密后的img地址
#加密就是经过js函数实现的,因此分析js函数,获知加密方式,而后进行解密。
#经过抓包工具抓取起始url的数据包,在数据包中全局搜索js函数名(jandan_load_img),而后分析该函数实现加密的方式。
#在该js函数中发现有一个方法调用,该方法就是加密方式,对该方法进行搜索
#搜索到的方法中会发现base64和md5等字样,md5是不可逆的因此优先考虑使用base64解密
#print(page_text)

tree = etree.HTML(page_text)
#在抓包工具的数据包响应对象对应的页面中进行xpath的编写,而不是在浏览器页面中。 #获取了加密的图片url数据 imgCode_list = tree.xpath('//span[@class="img-hash"]/text()') imgUrl_list = [] for url in imgCode_list: #base64.b64decode(url)为byte类型,须要转成str img_url = 'http:'+base64.b64decode(url).decode() imgUrl_list.append(img_url) for url in imgUrl_list: filePath = url.split('/')[-1] urllib.request.urlretrieve(url=url,filename=filePath) print(filePath+'下载成功')

      ● 解析58二手房的相关数据

# 58二手房信息
import requests

from lxml import etree

url = 'https://bj.58.com/ershoufang/sub/l16/s2242/?utm_source=market&spm=u-2d2yxv86y3v43nkddh1.bdpcpz_bt&PGTID=0d30000c-0000-1139-b00c-643d0d315a04&ClickID=1'
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
page_text = requests.get(url,headers=headers).text

tree = etree.HTML(page_text)
li_list = tree.xpath('//ul[@class="house-list-wrap"]/li')

for li in li_list:
    title = li.xpath('./div[2]/h2[1]/a/text()')[0]

    ● 下载彼岸网中图片数据 : 中文乱码问题

import os
import urllib
url = 'http://pic.netbian.com/4kmeinv/'
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
response = requests.get(url,headers=headers)
# print(response.encoding)      # ISO-8859-1
# response.encoding = 'utg-8'

if not os.path.exists('./imgs'):
    os.mkdir('./imgs')

page_text = response.text

tree = etree.HTML(page_text)
li_list = tree.xpath('//div[@class="slist"]/ul/li')
for li in li_list:
    img_name = li.xpath('./a/b/text()')[0]
    # 处理中文乱码
    img_name = img_name.encode('ISO-8859-1').decode('gbk')
    img_url = 'http://pic.netbian.com' + li.xpath('./a/img/@src')[0]
    img_path = './imgs/' + img_name + '.jpg'
    urllib.request.urlretrieve(url=img_url,filename=img_path)

    ● 下载站长素材中的简历模板数据 

import requests
from lxml import etree
import random
import os

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}

if not os.path.exists('./jianli'):
    os.mkdir('./jianli')

for i in range(1,4):
    if i == 1:
        url = 'http://sc.chinaz.com/jianli/free.html'
    else:
        url = 'http://sc.chinaz.com/jianli/free_%s.html' % (i)
    
    response = requests.get(url=url, headers=headers)
    response.encoding = 'utf8'

    res = response.text

    tree = etree.HTML(res)

    a_list = tree.xpath('//a[@class="title_wl"]')
    for a in a_list:
        name = a.xpath('./text()')[0]
        jl_url = a.xpath('./@href')[0]

        response = requests.get(url=jl_url, headers=headers)
        response.encoding = 'utf8'
        res1 = response.text
        tree = etree.HTML(res1)
        download_url_list = tree.xpath('//div[@class="clearfix mt20 downlist"]/ul/li/a/@href')
        download_url = random.choice(download_url_list)

        res3 = requests.get(url=download_url, headers=headers).content

        filepath = './jianli/' + name + '.rar'
        with open(filepath, 'wb') as f:
            f.write(res3)
        print(name, '下载完成!')

print('over')

    ● 解析全部城市的名称 

import requests
from lxml import etree

url = 'https://www.aqistudy.cn/historydata/'

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}

res = requests.get(url=url, headers=headers).text
tree = etree.HTML(res)
city_list = tree.xpath('//div[@class="bottom"]/ul/li/a/text() | //div[@class="bottom"]/ul/div[2]/li/a/text()')        # 能够用逻辑运算符,这里 | 表示或的关系
city = ''.join(city_list)

 

 三 . bs4 (Beautiful Soup) 解析 

  环境安装 : 
#- 须要将pip源设置为国内源,阿里源、豆瓣源、网易源等
  # - windows
    #(1)打开文件资源管理器(文件夹地址栏中)
    #(2)地址栏上面输入 %appdata%
    #(3)在这里面新建一个文件夹  pip
    #(4)在pip文件夹里面新建一个文件叫作  pip.ini ,内容写以下便可
        [global]
        timeout = 6000
        index-url = https://mirrors.aliyun.com/pypi/simple/
        trusted-host = mirrors.aliyun.com
   # - linux
    (1)cd ~2)mkdir ~/.pip
    (3)vi ~/.pip/pip.conf
    (4)编辑内容,和windows如出一辙
#- 须要安装: 咱们能够直接这样安装也能够 pip install bs4 # bs4在使用时候须要一个第三方库,把这个库也安装一下 pip install lxml

  基础使用 : 

使用流程:       
    - 导包:from bs4 import BeautifulSoup
    - 使用方式:能够将一个html文档,转化为BeautifulSoup对象,而后经过对象的方法或者属性去查找指定的节点内容
    1)转化本地文件:
             - soup = BeautifulSoup(open('本地文件'), 'lxml')
        2)转化网络文件:
             - soup = BeautifulSoup('字符串类型或者字节类型', 'lxml')
        3)打印soup对象显示内容为html文件中的内容

基础巩固:
    1)根据标签名查找
        - soup.a 只能找到第一个符合要求的标签
    2)获取属性
        - soup.a.attrs  获取a全部的属性和属性值,返回一个字典
        - soup.a.attrs['href']   获取href属性
        - soup.a['href'] 也可简写为这种形式
    3)获取内容
        - soup.a.string  获取直系标签内容
        - soup.a.text
        - soup.a.get_text() 【注意】若是标签还有标签,那么string获取到的结果为None,而其它两个,能够获取文本内容
    4)find:找到第一个符合要求的标签
        - soup.find('a')  找到第一个符合要求的
        - soup.find('a', title="xxx")
        - soup.find('a', alt="xxx")
        - soup.find('a', class_="xxx")
        - soup.find('a', id="xxx")
    5)find_all:找到全部符合要求的标签
        - soup.find_all('a')
        - soup.find_all(['a','b']) 找到全部的a和b标签
        - soup.find_all('a', limit=2)  限制前两个
   6)根据选择器选择指定的内容
               select:soup.select('#feng')
        - 常见的选择器:标签选择器(a)、类选择器(.)、id选择器(#)、层级选择器
            - 层级选择器:经常使用
                div .dudu #lala .meme .xixi  下面好多级
                div > p > a > .lala          只能是下面一级
        【注意】select选择器返回永远是列表,须要经过下标提取指定的对象
    使用bs4爬取诗词名句中的三国演义小说中的每一章的内容 
import requests
from bs4 import BeautifulSoup

url = 'http://www.shicimingju.com/book/sanguoyanyi.html'
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
}
#获取标题正文页数据
page_text = requests.get(url=url,headers=headers).text+

# 实例化 BeautifulSoup
# 将页面源码数据加载里面 , 参数1=page_text , 参数2="lxml" 解析器
soup = BeautifulSoup(page_text,'lxml')
#标签订位,返回的是一个列表,是标题
a_list = soup.select('.book-mulu > ul > li > a')
#由于内容是要循环的,全部文件打开一次就能够
fp = open('sanguo.txt','w',encoding='utf-8')
for a in a_list:
   # 获取a标签的直系标签的文本内容
    title = a.string
    #补全标题内容的地址
    detail_url = 'http://www.shicimingju.com'+a['href']
    #进入标题的url才是标题对应的内容
    detail_page_text = requests.get(url=detail_url,headers=headers).text
    
    soup = BeautifulSoup(detail_page_text,'lxml')
    content = soup.find('div',class_='chapter_content').text
    
    fp.write(title+'\n'+content)
    print(title,'下载完毕')
print('over')
fp.close()
import requests
from bs4 import BeautifulSoup

# 获取页面源文件
url = "https://www.23us.so/files/article/html/0/43/index.html"

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
}

page_text = requests.get(url=url,headers=headers)
#防止中文文字出现乱码
page_text.encoding = "utf8"

page_text = page_text.text
# 实例化 BeautifulSoup
# 将页面源码数据加载里面 , 参数1=page_text , 参数2="lxml" 解析器
soup = BeautifulSoup(page_text,"lxml")

# 标签订位,HTML的标签
# 先解析源码中标题所对的a标签  层级 .表明id
# 返回一个列表
a_list = soup.select(".L > a")

f1 = open('三寸人间2.text','w',encoding="utf8")

# 遍历列表,获取a标签的本文和 href 值
# 获取章节目录
# a表示<a href="/10/10489/4535761.html">第一章 我要减肥!</a>
# a.string 获取标签直系的文本内容,返回字符串

for a in a_list:
    title = a.string
    #补全域名 http://www.xbiquge.la + deatil_url  
    detatil_url = a["href"]
   # 获取详情页的源码数据
    detail_page_text = requests.get(url=detatil_url,headers=headers).content
    print('3333333333',detail_page_text)
    
    soup = BeautifulSoup(detail_page_text,"lxml")
   # 获取文本内容 ,div 
    content = soup.find('dd',id='contents').text
    # 持久化存储
    f1.write(title+'\n'+content)
    print(title,"下载ok")
    
print("ok")
f1.close()
实现笔趣阁的小说--三寸人间

 

四 . 图片的懒加载

    示例网站 : http://sc.chinaz.com/tupian/hunsha.html
    就是在打开网站以后图片并非所有加载出来,而是在你的鼠标向下滑动的时候在加载(滑动一点加载一点)
import requests
from lxml import etree
import os
import urllib

if not os.path.exists('./tupian'):
    os.mkdir('./tupian')

url = 'http://sc.chinaz.com/tupian/'

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}

response = requests.get(url=url, headers=headers)
response.encoding = 'utf8'
res = response.text
tree = etree.HTML(res)
url_list = tree.xpath('//div[@id="container"]/div/div/a/img/@src2')         
# img标签有伪属性src2,当图片滚动到视野内时变为 src for url in url_list: filepath = './tupian/' + url.rsplit('/',1)[-1] urllib.request.urlretrieve(url, filepath) print(filepath, '下载完成!') print('over')

 

五 . 代理ip 

  • 什么是代理
    • 代理就是第三方代替本体处理相关事务。例如:生活中的代理:代购,中介,微商......

  • 爬虫中为何须要使用代理

    • 一些网站会有相应的反爬虫措施,例如不少网站会检测某一段时间某个IP的访问次数,若是访问频率太快以致于看起来不像正常访客,它可能就会会禁止这个IP的访问。因此咱们须要设置一些代理IP,每隔一段时间换一个代理IP,就算IP被禁止,依然能够换个IP继续爬取。

  • 代理的分类:

    • 正向代理:代理客户端获取数据。正向代理是为了保护客户端防止被追究责任。

    • 反向代理:代理服务器提供数据。反向代理是为了保护服务器或负责负载均衡。

  • 免费代理ip提供网站

    • http://www.goubanjia.com/

    • 西祠代理

    • 快代理  

  • 代理ip的匿名度分为三个等级:

    高匿:服务器不知道你使用了代理,并没有法获取你的真实IP;

    普匿:服务器能知道你使用了代理,可是没法获取你的真实IP地址;

    透明:服务器能知道你使用了代理,并能获取你的真实IP地址。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import random
if __name__ == "__main__":
    #不一样浏览器的UA
    header_list = [
        # 遨游
        {"user-agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)"},
        # 火狐
        {"user-agent": "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"},
        # 谷歌
        {
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"}
    ]
    #不一样的代理IP
    proxy_list = [
        {"http": "112.115.57.20:3128"},
        {'http': '121.41.171.223:3128'}
    ]
    #随机获取UA和代理IP
    header = random.choice(header_list)
    proxy = random.choice(proxy_list)

    url = 'http://www.baidu.com/s?ie=UTF-8&wd=ip'
    #参数3:设置代理
    response = requests.get(url=url,headers=header,proxies=proxy)
    response.encoding = 'utf-8'
    
    with open('daili.html', 'wb') as fp:
        fp.write(response.content)
    #切换成原来的IP
    requests.get(url, proxies={"http": ""})

 

六 . 总结 : 目前学过的反爬机制 

  - robots.txt 
  - UA
  - 数据加密
  - 懒加载
  - 代理ip