爬虫2(一)

一.爬虫介绍

爬虫是什么:
    爬虫是一个模仿浏览器行为的向服务器发送请求并且获得数据的应用程序

爬虫的比喻:
    互联网好比一张大网,数据是网上的猎物,爬虫就是蜘蛛

爬虫的价值:
    数据的价值

爬虫的流程:
    发起请求-获取数据--解析数据--存储数据

二.http协议相关

请求:
    Request URL:要去哪儿
    Request Method:
        get:
            ?ziduan=zhi&ziduan=zhi
        post:
            请求体:
                formdata
                json
                files
    请求头:
        Cookie:保存信息(主要:记录用户登录状态)
        User-Agent:用户身份
        referer:告诉服务器,你从哪里来
        服务器特有字段

响应:
    Status Code:
        2xx:
            请求成功
        3xx:
            重定向
        4xx:
        5xx:
    响应头:
        location:重定向的url
        set—cookie:设置cookie
        服务器特定字段
    响应体:
        1.html代码
        2.二进制:图片,视频,音频
        3.json
        4.jsonp

三.请求库

 1.url后拼接参数如果和params重复,以列表方式并存;

 2.header中的cookie与cookies重复,优先显示header中的cookie;

 3.json与data不能共存;

 4.把cookie保存到本地要导入import http.cookiejar as cookiejar,保存用save方法

 5.history以列表套对象方式记录重定向

'''
requests
'''
import requests

# requests.get()
# requests.post()
# requests.request(method='post')


#get请求
url = 'http://httpbin.org/get?name=mac&age=20&xxx=1000&xxx=yyy'

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",
    'Cookie':'aaa=123;bbb=234'
}

params = {
    'zzz':'mmm',
}

cookies = {
    'ccc':'999'
}

# url = 'http://www.tmall.com'
#
# r = requests.get(url=url,headers=headers,params=params,cookies=cookies,allow_redirects=True)
# print(r.headers)


#post请求
# url = 'http://httpbin.org/post'
#
# data = {
#     'name':'mac',
# }
#
# json = {
#     'age':18
# }
#
# json = [1,True]
#
# files = {
#     'files':open('xxx.txt','rt',encoding='utf-8')
# }
#
# r = requests.post(url=url,files=files)
# print(r.text)



# url = 'http://www.tmall.com'
# r = requests.get(url=url)
# print(r.history[0].url)
# print(r.url)


# session = requests.session()
# r = session.get('http://www.baidu.com')
# print(r.cookies)
# r = session.get('http://httpbin.org/get')
# print(r.text)

# import http.cookiejar as cookiejar
#
# session = requests.session()
# session.cookies = cookiejar.LWPCookieJar()
#
# session.cookies.load('1.txt')
# print(session.cookies)
# r = session.get('http://www.baidu.com')
# session.cookies.save('1.txt')


r = requests.get(url='http://www.xiaohuar.com')
print(r.text)
**安装**:pip install requests

​    **使用**:

​        **请求**:

​            **①get请求:**

```
                响应对象 = requests.get(......)

​                **参数:**

​                    url:

​                    headers = {}

​                    cookies = {}

​                    params = {}    

​                    proxies = {'http':‘http://端口:ip’}

​                    timeout = 0.5

​                    allow_redirects = False
```



​            **②post请求:**

```
                响应对象 = requests.post(......)

​                **参数:**

​                    url:

​                    headers = {}

​                    cookies = {}

​                    data = {}

​                    json = {}

​                    files = {‘file’:open(...,‘rb’)}

​                    timeout = 0.5

​                    allow_redirects = False
```

​        **自动保存cookie的请求:**

```
            session = requests.session()

​            r = session.get(......)

​            r = session.post(......)
      补充:(保存cookie到本地)
          import http.cookiejar as cookielib
          session.cookie = cookielib.LWPCookieJar()
          session.cookie.save(filename='1.txt')
          
          session.cookies.load(filename='1.txt')
```

​        **响应:**

```
            r.url                    请求url

​            r.text                    获得响应体文本信息

​            r.encoding = 'gbk'        

​            r.content                二进制

​            r.json()                json.loads(r.text)

​            r.status_code            

​            r.headers

​            r.cookies                拿cookie

​            r.history                【相对对象1,响应对象2,。。。】
```

四.解析相关(css选择器)

​    1、类选择器

​        .类名

​    2、id选择器

​        #id值
3、标签选择器

​        标签名

​    4、后代选择器

​            选择器1 选择器2

​    5、子选择器

​            选择器1>选择器2

​    6、属性选择器

​        [属性名]

​        【属性名=属性值】

​        【属性名^=值】、

​        【属性名$=值】

​        【属性名*=值】



​    7、群组选择器

​        选择器1,选择器2.。。     or8、多条件选择器

​        选择器1选择器2            and

五.requests-html

**安装:** pip install requests-html

​    **使用:****请求:**

```
            from requests_html import HTMLSession

​            session = HTMLSession()

​            **参数:**

​                browser.args = [

​                    '--no-sand',

​                    '--user-agent=XXXXX'

​                ]

​            响应对象 = session.request(......)

​            响应对象 = session.get(......)

​            响应对象 = session.post(......)
```

​            **参数和requests模块一毛一样****响应:**

```
            r.url

​            **属性和requests模块一毛一样
```

****解析:****html对象属性:**

```
            r.html.absolute_links       绝对路径

​                       .links           相对路径

​                       .base_url        根路径

​                       .html            相当于r.text
 
​                       .text            获取页面所有标签内容

​                       .encoding = 'gbk'   (document.charset可查看编码)

​                       .raw_html        相当于r.html(二进制流)

​                       .pq              调pyquery库
```

​        **html对象方法:**

```
            r.html.find('css选择器')                         [element1,.......]

​                   .find('css选择器',first = True)           element1

​                   .xpath(‘xpath选择器’)

​                   .xpath('‘xpath选择器',first = True)

​                   .search(‘模板’)

​                            (‘xxx{}yyy{}’)[0]

​                            (‘xxx{name}yyy{pwd}’)[‘name’]

​                   .search_all('模板')

​                   .render(.....)       r.html.html = 渲染后html文本

​                       **参数:**

​                            scripy:“”“ ( ) => {

​                                        js代码

​                                        js代码

​                                    }

​                                  ”“”

​                            scrolldow:n

​                            sleep:n

​                            keep_page:True/False  防止浏览器关闭
```


绕过浏览器检测
```
()=>{
Object.defineProperties(navigator,{
        webdriver:{
        get: () => undefined
        }
    })
```

​        **与浏览器交互    r.html.page.XXX**

```
                asynic def xxx():

​                    await r.html.page.XXX

​                session.loop.run....(xxx())

​            .screenshot({'path':路径})

​            .evaluate('''() =>{js代码}’‘’})

​            .cookies()

​            .type('css选择器',’内容‘,{’delay‘:100})

​            .click('css选择器')

​            .focus('css选择器')

​            .hover('css选择器')

​            .waitForSelector('css选择器')

​            .waitFor(1000)
```

​        **键盘事件    r.html.page.keyboard.XXX**

```
            .down('Shift')

​            .up('Shift')

​            .press('ArrowLeft')

​            .type('喜欢你啊',{‘delay’:100})
```

​        **鼠标事件    r.html.page.mouse.XXX**

​            

```
            .click(x,y,{
                'button':'left',
                'click':1
                'delay':0
            })
            .down({'button':'left'})
            .up({'button':'left'})
            .move(x,y,{'steps':1})

```

​            .

element属性:

 a = r.html.find('[class="special"] dd a',first=True)
 print(a.absolute_links)
 print(a.links)
 print(a.text)
 print(a.html)
 print(a.attrs.get('href'))

常用数据库

###mongoDB4.0(不在c盘要删除配置文件中的最后一行):

下载:https://www.mongodb.com/

安装:略

注意:使用前修改bin目录下配置文件mongodb.cfg,删除最后一行的'mp'字段

####1. 启动服务与终止服务

net start mongodb

net stop mongodb

2.创建管理员用户

mongo

use admin

db.createUser({user:"yxp",pwd:"997997",roles:["root"]})

3.使用账户密码连接mongodb

mongo -u adminUserName -p userPassword --authenticationDatabase admin

4.数据库

查看数据库
show dbs 查看数据库
切换数据库
 use db_name 切换数据库
增加数据库
db.table1.insert({'a':1})  创建数据库(切换到数据库插入表及数据)
删除数据库
db.dropDatabase()  删数据库(删前要切换)

5.表

使用前先切换数据库
查看表
show tables 查所有的表
增加表
db.table1.insert({'b':2})  增加表(表不存在就创建)
删除表
db.table1.drop()    删表

数据

db.test.insert(user0)    插入一条
db.user.insertMany([user1,user2,user3,user4,user5])   插入多条
db.user.find({'name':'alex'})   查xx==xx
db.user.find({'name':{"$ne":'alex'}})   查xx!=xx
db.user.find({'_id':{'$gt':2}})   查xx>xx
db.user.find({"_id":{"$gte":2,}}) 查xx>=xx
db.user.find({'_id':{'$lt':3}}) 查xx<xx
db.user.find({"_id":{"$lte":2}}) 查xx<=xx
db.user.update({'_id':2},{"$set":{"name":"WXX",}})   改数据
db.user.deleteOne({ 'age': 8 })   删第一个匹配
db.user.deleteMany( {'addr.country': 'China'} ) 删全部匹配
db.user.deleteMany({}) 删所有

pymongo

conn = pymongo.MongoClient(host=host,port=port, username=username, password=password)
db = client["db_name"] 切换数据库
table = db['表名']
table.insert({}) 插入数据
table.remove({})   删除数据
table.update({'_id':2},{"$set":{"name":"WXX",}})   改数据
table.find({}) 查数据

 

 

posted @ 2019-10-17 23:04  纵横捭阖行  阅读(141)  评论(0编辑  收藏  举报