简单爬虫的相关知识点

简单的爬虫
from urllib.request import urlopen

url="http://www.baidu.com"
response=urlopen(url) #发送请求,返回响应
info=response.read()#读取内容

print(info.decode())#打印内容
print(response.getcode())#打印状态码
print('真是的url:'+response.geturl())#打印真实的url
print(response.info())#打印响应头

伪装自己

Request的使用
headers={
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
}
request=Request(url,headers=headers)
response=urlopen(request)

多个User-Agent随机使用

user_agents=[
    "User-Agent:Mozilla/5.0(Windows;U;WindowsNT6.1;en-us)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50",
    "User-Agent:Mozilla/5.0(WindowsNT6.1;rv:2.0.1)Gecko/20100101Firefox/4.0.1",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
]
headers={
    "User-Agent":choice(user_agents)
}

使用fake-useragent

  1. 安装
pip install fake-useragent
  1. 使用
from fake_useragent import UserAgent

ua=UserAgent()
print(ua.chrome)

get请求

  • 大部分被传输到浏览器的html,images,js,css,…都是通过get方法发送请求的,它是获取数据的主要方法
  • GET请求的参数都是在URL中体现的,例如:https://www.baidu.com/s?wd=西安邮电大学&ie=utf-8&,如果有中文,则需要转码,使用下面两张方法进行转码
    • urllib.parse.quote
    from urllib.parse import quote
    url="http://www.baidu.com/s?wd={}".format(quote("西安邮电大学"))
    #url的输出结果为http://www.baidu.com/s?wd=西安邮电大学
    
    • urllib.parse.urlencode
    from urllib.parse import urlencode
    args={
        "wd":"西安邮电大学",
        "ie":"utf-8"
    }
    url="http://www.baidu.com/s?{}".format(urlencode(args))
    #url的输出结果为http://www.baidu.com/s?wd=西安邮电大学&ie=utf-8
    

post

  • Request请求对象里data参数,它就是用在POST里的,我们要传送的数据就是这个参数data,data是一个字典,
  • 代码:
#此代码只写了和post请求有关的,其他没变的代码在此省略,可查看上面的代码
#此博客的好多代码都是只写了部分代码
datas={
    "user":"17703181473",
    "password":"123456"
}
url="https://www.sxt.cn/index/login/login.html"
request=Request(url,headers=headers,data=urlencode(datas).encode())
#最终的输出结果会看到登录成功的字样,当然,用户名或密码错了会看到用户名或密码不正确的字样

请求SSL证书验证

import ssl
context=ssl._create_unverified_context()#加入这行代码
reponse=urlopen(request,context=context)#加入上面的context

build_openerd和ProxyHandler的使用

  • 透明代理:目标网站知道你使用了代理并且知道你的源IP地址,这种代理显然不符合我们我们使用代理的初衷
  • 匿名代理:匿名程度比较低,也就是网站知道你是用了代理,但是并不知道你使用的源IP地址
  • 高级代理:这是最保险的方式,目标网站既不知道你使用的代理更不知道你的源IP
  • 代码:
from urllib.request import build_opener,Request,ProxyHandler

#handler=ProxyHandler({"http":"password@ip:port"})
#handler=ProxyHandler({"http":"398707160:j8inhg2g@120.27.224.41:16818"})
#proxy=ProxyHandler({"http":"ip:port"})
proxy=ProxyHandler({"http":"118.190.95.43:9001"})
opener=build_opener(proxy)
response=opener.open(request)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值