zoukankan      html  css  js  c++  java
  • Python爬虫入门这一篇就够了

    何谓爬虫

    所谓爬虫,就是按照一定的规则,自动的从网络中抓取信息的程序或者脚本。万维网就像一个巨大的蜘蛛网,我们的爬虫就是上面的一个蜘蛛,不断的去抓取我们需要的信息。

    爬虫三要素

    • 抓取
    • 分析
    • 存储

    基础的抓取操作

    1、urllib
    在Python2.x中我们可以通过urllib 或者urllib2 进行网页抓取,但是再Python3.x 移除了urllib2。只能通过urllib进行操作

    import urllib.request
    
    response = urllib.request.urlopen('https://blog.csdn.net/weixin_43499626')
    print(response.read().decode('utf-8'))
    

      

    带参数的urllib

    url = 'https://blog.csdn.net/weixin_43499626'
    url = url + '?' + key + '=' + value1 + '&' + key2 + '=' + value2
    

      

    2、requests

    requests库是一个非常实用的HTPP客户端库,是抓取操作最常用的一个库。Requests库满足很多需求

    import requests
    # get请求
    response = requests.get(url='https://blog.csdn.net/weixin_43499626')  
    print(response.text)   #打印解码后的返回数据
    # 带参数的requests get请求
    response = requests.get(url='https://blog.csdn.net/weixin_43499626', params={'key1':'value1', 'key2':'value2'}) 

    需要登录的情况下

    1、表单提交登录
    向服务器发送一个post请求并携带相关参数,将服务器返回的cookie保存在本地,cookie是服务器在客户端上的“监视器”,记录了登录信息等。客户端通过识别请求携带的cookie,确定是否登录

    params = {'username': 'root', 'passwd': 'root'}
    response = requests.post("http:xxx.com/login", data=params)
    for key,value in response.cookies.items():
        print('key = ', key + ' ||| value :'+ value)
    

     

    2、cookie登录
    我们可以将登录的cookie存储在文件中,

    import urllib.request
    import http.cookiejar
    """
    保存登录的cookie
    """
    """
    MozillaCookieJar : cookiejar的子类
    从FileCookieJar派生而来,创建与Mozilla浏览器 cookies.txt兼容的FileCookieJar实例。
    """
    cookie = http.cookiejar.MozillaCookieJar('cookie.txt')
    # 构建一个cookie的处理器
    handler = urllib.request.HTTPCookieProcessor(cookie)
    # 获取一个opener对象
    opener = urllib.request.build_opener(handler)
    # # 获取一个请求对象
    request = urllib.request.Request('http://flights.ctrip.com/',headers={"Connection": "keep-alive"})
    # 请求服务器,获取响应对象。cookie会在response里一起响应
    response = opener.open(request)
    # 保存cookie到文件
    cookie.save(ignore_discard=True, ignore_expires=True)
    
    
    """
    请求携带文件中的cookie
    """
    
    import urllib.request
    import http.cookiejar
    cookie = http.cookiejar.MozillaCookieJar()
    cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
    handler = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(handler)
    request = urllib.request.Request('http://flights.ctrip.com/')
    html = opener.open(request).read().decode('gbk')
    
    print(html)
    

      

     

    常见的反爬有哪些

    1、通过user-agent来控制访问
    user-agent能够使服务器识别出用户的操作系统及版本、cpu类型、浏览器类型和版本。很多网站会设置user-agent白名单,只有在白名单范围内的请求才能正常访问。所以在我们的爬虫代码中需要设置user-agent伪装成一个浏览器请求。有时候服务器还可能会校验Referer,所以还可能需要设置Referer(用来表示此时的请求是从哪个页面链接过来的)

    # 设置请求头信息
    headers = {
            'Host': 'https://blog.csdn.net',
            'Referer': 'https://blog.csdn.net/weixin_43499626/article/details/85875090',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
        }
    response = requests.get("http://www.baidu.com", headers=headers) 
     

    如下是CSDN中的Request Header中的信息

    accept: */*
    accept-encoding: gzip, deflate, br
    accept-language: zh-CN,zh;q=0.9
    content-length: 0
    cookie: bdshare_firstime=1500xxxxxxxx..............
    origin: https://blog.csdn.net
    referer: https://blog.csdn.net/weixin_43499626/article/details/85875090
    user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
    x-requested-with: XMLHttpRequest
    

      

    2、通过IP来限制

    当我们用同一个ip多次频繁访问服务器时,服务器会检测到该请求可能是爬虫操作。因此就不能正常的响应页面的信息了。
    解决办法常用的是使用IP代理池。网上就有很多提供代理的网站、

    proxies = {
      "http": "http://119.101.125.56",
      "https": "http://119.101.125.1",
    }
    response = requests.get("http://www.baidu.com", proxies=random.choices(proxies)) 
    

      

    3、设置请求间隔

    import time
    time.sleep(1)
    

      

    4、自动化测试工具Selenium
    Web应用程序测试的Selenium工具。该工具可以用于单元测试,集成测试,系统测试等等。它可以像真正的用户一样去操作浏览器(包括字符填充、鼠标点击、获取元素、页面切换),支持Mozilla Firefox、Google、Chrome、Safari、Opera、IE等等浏览器。

    5、参数通过加密
    某些网站可能会将参数进行某些加密,或者对参数进行拼接发送给服务器,以此来达到反爬虫的目的。这个时候我们可以试图通过js代码,查看破解的办法。
    连接xxx
    或者可以使用"PhantomJS",PhantomJS是一个基于Webkit的"无界面"(headless)浏览器,它会把网站加载到内存并执行页面上的JavaScript,因为不会展示图形界面,所以运行起来比完整的浏览器更高效。

    6、通过robots.txt来限制爬虫

    robots.txt是一个限制爬虫的规范,该文件是用来声明哪些东西不能被爬取。如果根目录存在该文件,爬虫就会按照文件的内容来爬取指定的范围。

    浏览器访问https://www.taobao.com/robots.txt
    可以查看淘宝的robots.txt文件
    部分内容如下

    User-agent:  Baiduspider
    Disallow:  /product/
    Disallow:  /
    
    User-Agent:  Googlebot
    Disallow:  /
    
    User-agent:  Bingbot
    Disallow:  /
    
    User-Agent:  360Spider
    Disallow:  /
    
    User-Agent:  Yisouspider
    Disallow:  /
    
    User-Agent:  Sogouspider
    Disallow:  /
    
    User-Agent:  Yahoo!  Slurp
    Disallow:  /
    
    User-Agent:  *
    Disallow:  /
     

    可以看出淘宝拒绝了百度爬虫、谷歌爬虫、必应爬虫、360爬虫、神马爬虫,搜狗爬虫、雅虎爬虫等约束。

    分析

    我们可以分析爬取的网页内容,获得我们真正需要的数据,常用的有正则表达式,BeautifulSoup,XPath、lxml等

    正则表达式是进行内容匹配,将符合要求的内容全部获取;
    xpath()能将字符串转化为标签,它会检测字符串内容是否为标签,但是不能检测出内容是否为真的标签;
    Beautifulsoup是Python的一个第三方库,它的作用和 xpath 作用一样,都是用来解析html数据的相比之下,xpath的速度会快一点,因为xpath底层是用c来实现的

    存储

    通过分析网页内容,获取到我们想要的数据,我们可以选择存到文本文件中,亦可以存储在数据库中,常用的数据库有MySql、MongoDB

    存储为json文件

    import json
    
    dictObj = {
        '小明':{
            'age': 15,
            'city': 'beijing',
        },
        '汤姆': {
            'age': 16,
            'city': 'guangzhou',
        }
    }
    
    jsObj = json.dumps(dictObj, ensure_ascii=False)
    fileObject = open('jsonFile.json', 'w')
    fileObject.write(jsObj)
    fileObject.close()
    

     

    存储为cvs文件

    import csv
    with open('student.csv', 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['姓名', '年龄', '城市'])
        writer.writerows([['小明', 15 , '北京'],['汤姆', 16, '广州']])
    

      

    存储到Mongo

    # mongo服务
    client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
    # test数据库
    db = client.test
    # student表,没有自动创建
    student_db = db.student
    student_json = {
        'name': '小明',
        'age': 15,
        'city': '北京'
    }
    student_db.insert(student_json)
    

      


    最后推荐一下我自学爬虫时看过的《Python3网络爬虫开发实战》:

    链接:https://pan.baidu.com/s/1_hSYBZk3F_a4SXz0YTUQ8A
    提取码:6oxu

     
  • 相关阅读:
    文件上传案例_Socket_测试
    Linux的小整理(入门)
    full stack 第一天
    基础考题 试题
    shell语法
    网络管理
    图像类
    定时储存
    网络管理
    磁盘管理
  • 原文地址:https://www.cnblogs.com/wyl-0120/p/10358086.html
Copyright © 2011-2022 走看看