我们在编写Python爬虫时,有时会遇到网站拒绝访问等反爬手段,比如这么我们想爬取蚂蚁短租数据,它则会提示“当前访问疑似黑客攻击,已被网站管理员设置为拦截”提示,如下图所示。此时我们需要采用设置Cookie来进行爬取,下面我们进行详细介绍。非常感谢我的学生承峰提供的思想,后浪推前浪啊!
一. 网站分析与爬虫拦截
当我们打开蚂蚁短租搜索贵阳市,反馈如下图所示结果。
我们可以看到短租房信息呈现一定规律分布,如下图所示,这也是我们要爬取的信息。
通过浏览器审查元素,我们可以看到需要爬取每条租房信息都位于<dd></dd>节点下。
在定位房屋名称,如下图所示,位于<div class="room-detail clearfloat"></div>节点下。
接下来我们写个简单的BeautifulSoup进行爬取。
# -*- coding: utf-8 -*-
import urllib
import re
from bs4 import BeautifulSoup
import codecs
url = 'http://www.mayi.com/guiyang/?map=no'
response=urllib.urlopen(url)
contents = response.read()
soup = BeautifulSoup(contents, "html.parser")
print soup.title
print soup
#短租房名称
for tag in soup.find_all('dd'):
for name in tag.find_all(attrs={"class":"room-detail clearfloat"}):
fname = name.find('p').get_text()
print u'[短租房名称]', fname.replace('\n','').strip()
但很遗憾,报错了,说明蚂蚁金服防范措施还是挺到位的。
二. 设置Cookie的BeautifulSoup爬虫
添加消息头的代码如下所示,这里先给出代码和结果,再教大家如何获取Cookie。
# -*- coding: utf-8 -*-
import urllib2
import re
from bs4 import BeautifulSoup
#爬