Python 网络爬虫--简单的爬取一些防爬取的网站

网站防采集的前提就是要正确地区分人类访问用户和网络机器人。虽然网站可以使用很多识别技术(比如验证码)来防止爬虫,但还是有一些十分简单的方法,可以让你的网络机器人看起来更像人类访问用户。

构造HTTP 请求头,可以使机器人网络爬取机器人更像一个访问用户

1.在没有使用HTTP请求头时,我们来获取CSDN一篇博客的网页内容时情况是这样的:

代码如下:

# coding utf-8
import requests

def get_content():
    html = requests.get("http://blog.csdn.net/m_wbcg/article/details/70243372")
    return html.text

print(get_content())

结果:

<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>

请求被禁止掉了

2.使用HTTP请求头时。

代码如下:

# coding utf-8
import requests

def get_content():
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
    }
    html = requests.get("http://blog.csdn.net/m_wbcg/article/details/70243372",headers=header)
    return html.text

print(get_content())

结果:

这次我们就得到了我们想得到的结果了

构造合理的HTTP请求头只是最简单的一种方法

最后推荐一篇博客:http://www.cnblogs.com/junrong624/p/5533655.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值