Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题


Posted in Python onFebruary 22, 2021

我们在编写Python爬虫时,有时会遇到网站拒绝访问等反爬手段,比如这么我们想爬取蚂蚁短租数据,它则会提示“当前访问疑似黑客攻击,已被网站管理员设置为拦截”提示,如下图所示。此时我们需要采用设置Cookie来进行爬取,下面我们进行详细介绍。非常感谢我的学生承峰提供的思想,后浪推前浪啊!

一. 网站分析与爬虫拦截

当我们打开蚂蚁短租搜索贵阳市,反馈如下图所示结果。

Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题

我们可以看到短租房信息呈现一定规律分布,如下图所示,这也是我们要爬取的信息。

Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题

通过浏览器审查元素,我们可以看到需要爬取每条租房信息都位于<dd></dd>节点下。

Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题

很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!
QQ群:810735403

在定位房屋名称,如下图所示,位于<div class="room-detail clearfloat"></div>节点下。

Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题

接下来我们写个简单的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()

但很遗憾,报错了,说明蚂蚁金服防范措施还是挺到位的。

Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题

二. 设置Cookie的BeautifulSoup爬虫

添加消息头的代码如下所示,这里先给出代码和结果,再教大家如何获取Cookie。

# -*- coding: utf-8 -*-
import urllib2
import re
from bs4 import BeautifulSoup
 
#爬虫函数
def gydzf(url):
 user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
 headers={"User-Agent":user_agent}
 request=urllib2.Request(url,headers=headers)
 response=urllib2.urlopen(request)
 contents = response.read()
 soup = BeautifulSoup(contents, "html.parser")
 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()
 #短租房价格
 for price in tag.find_all(attrs={"class":"moy-b"}):
 string = price.find('p').get_text()
 fprice = re.sub("[¥]+".decode("utf8"), "".decode("utf8"),string)
 fprice = fprice[0:5]
 print u'[短租房价格]', fprice.replace('\n','').strip()
 #评分及评论人数
 for score in name.find('ul'):
 fscore = name.find('ul').get_text()
 print u'[短租房评分/评论/居住人数]', fscore.replace('\n','').strip()
 #网页链接url
 url_dzf = tag.find(attrs={"target":"_blank"})
 urls = url_dzf.attrs['href']
 print u'[网页链接]', urls.replace('\n','').strip()
 urlss = 'http://www.mayi.com' + urls + ''
 print urlss
 
#主函数
if __name__ == '__main__':
 i = 1
 while i<10:
 print u'页码', i
 url = 'http://www.mayi.com/guiyang/' + str(i) + '/?map=no'
 gydzf(url)
 i = i+1
 else:
 print u"结束"

输出结果如下图所示:

页码 1
[短租房名称] 大唐东原财富广场--城市简约复式民宿
[短租房价格] 298
[短租房评分/评论/居住人数] 5.0分·5条评论·二居·可住3人
[网页链接] /room/851634765
http://www.mayi.com/room/851634765
[短租房名称] 大唐东原财富广场--清新柠檬复式民宿
[短租房价格] 568
[短租房评分/评论/居住人数] 2条评论·三居·可住6人
[网页链接] /room/851634467
http://www.mayi.com/room/851634467
 
...
 
页码 9
[短租房名称] 【高铁北站公园旁】美式风情+超大舒适安逸
[短租房价格] 366
[短租房评分/评论/居住人数] 3条评论·二居·可住5人
[网页链接] /room/851018852
http://www.mayi.com/room/851018852
[短租房名称] 大营坡(中大国际购物中心附近)北欧小清新三室
[短租房价格] 298
[短租房评分/评论/居住人数] 三居·可住6人
[网页链接] /room/851647045
http://www.mayi.com/room/851647045

Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题

接下来我们想获取详细信息

Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题

这里作者主要是提供分析Cookie的方法,使用浏览器打开网页,右键“检查”,然后再刷新网页。在“NetWork”中找到网页并点击,在弹出来的Headers中就隐藏这这些信息。

Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题

最常见的两个参数是Cookie和User-Agent,如下图所示:

Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题

然后在Python代码中设置这些参数,再调用Urllib2.Request()提交请求即可,核心代码如下:

user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... Chrome/61.0.3163.100 Safari/537.36"
 cookie="mediav=%7B%22eid%22%3A%22387123...b3574ef2-21b9-11e8-b39c-1bc4029c43b8"
 headers={"User-Agent":user_agent,"Cookie":cookie}
 request=urllib2.Request(url,headers=headers)
 response=urllib2.urlopen(request)
 contents = response.read()
 soup = BeautifulSoup(contents, "html.parser")
 for tag1 in soup.find_all(attrs={"class":"main"}):

注意,每小时Cookie会更新一次,我们需要手动修改Cookie值即可,就是上面代码的cookie变量和user_agent变量。完整代码如下所示:

import urllib2
import re
from bs4 import BeautifulSoup
import codecs
import csv
 
c = open("ycf.csv","wb") #write 写
c.write(codecs.BOM_UTF8)
writer = csv.writer(c)
writer.writerow(["短租房名称","地址","价格","评分","可住人数","人均价格"])
 
#爬取详细信息
def getInfo(url,fname,fprice,fscore,users):
 #通过浏览器开发者模式查看访问使用的user_agent及cookie设置访问头(headers)避免反爬虫,且每隔一段时间运行要根据开发者中的cookie更改代码中的cookie
 user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
 cookie="mediav=%7B%22eid%22%3A%22387123%22eb7; mayi_uuid=1582009990674274976491; sid=42200298656434922.85.130.130"
 headers={"User-Agent":user_agent,"Cookie":cookie}
 request=urllib2.Request(url,headers=headers)
 response=urllib2.urlopen(request)
 contents = response.read()
 soup = BeautifulSoup(contents, "html.parser")
 #短租房地址
 for tag1 in soup.find_all(attrs={"class":"main"}):
 print u'短租房地址:'
 for tag2 in tag1.find_all(attrs={"class":"desWord"}):
 address = tag2.find('p').get_text()
 print address
 #可住人数
 print u'可住人数:'
 for tag4 in tag1.find_all(attrs={"class":"w258"}):
 yy = tag4.find('span').get_text()
 print yy
 fname = fname.encode("utf-8")
 address = address.encode("utf-8")
 fprice = fprice.encode("utf-8")
 fscore = fscore.encode("utf-8")
 fpeople = yy[2:3].encode("utf-8")
 ones = int(float(fprice))/int(float(fpeople))
 #存储至本地
 writer.writerow([fname,address,fprice,fscore,fpeople,ones])
 
#爬虫函数
def gydzf(url):
 user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
 headers={"User-Agent":user_agent}
 request=urllib2.Request(url,headers=headers)
 response=urllib2.urlopen(request)
 contents = response.read()
 soup = BeautifulSoup(contents, "html.parser")
 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()
 #短租房价格
 for price in tag.find_all(attrs={"class":"moy-b"}):
 string = price.find('p').get_text()
 fprice = re.sub("[¥]+".decode("utf8"), "".decode("utf8"),string)
 fprice = fprice[0:5]
 print u'[短租房价格]', fprice.replace('\n','').strip()
 #评分及评论人数
 for score in name.find('ul'):
 fscore = name.find('ul').get_text()
 print u'[短租房评分/评论/居住人数]', fscore.replace('\n','').strip()
 #网页链接url
 url_dzf = tag.find(attrs={"target":"_blank"})
 urls = url_dzf.attrs['href']
 print u'[网页链接]', urls.replace('\n','').strip()
 urlss = 'http://www.mayi.com' + urls + ''
 print urlss
 getInfo(urlss,fname,fprice,fscore,user_agent)
 
#主函数
if __name__ == '__main__':
 i = 0
 while i<33:
 print u'页码', (i+1)
 if(i==0):
 url = 'http://www.mayi.com/guiyang/?map=no'
 if(i>0):
 num = i+2 #除了第一页是空的,第二页开始按2顺序递增
 url = 'http://www.mayi.com/guiyang/' + str(num) + '/?map=no'
 gydzf(url)
 i=i+1
 
c.close()

输出结果如下,存储本地CSV文件:

Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题

同时,大家可以尝试Selenium爬取蚂蚁短租,应该也是可行的方法。

到此这篇关于Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的文章就介绍到这了,更多相关Python爬虫爬取蚂蚁短租内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
使用Python &amp; Flask 实现RESTful Web API的实例
Sep 19 Python
Python实现读取Properties配置文件的方法
Mar 29 Python
Python3爬虫使用Fidder实现APP爬取示例
Nov 27 Python
Python queue队列原理与应用案例分析
Sep 27 Python
PyQt5高级界面控件之QTableWidget的具体使用方法
Feb 23 Python
15行Python代码实现免费发送手机短信推送消息功能
Feb 27 Python
python爬虫爬取淘宝商品比价(附淘宝反爬虫机制解决小办法)
Dec 03 Python
Python3+Flask安装使用教程详解
Feb 16 Python
pytorch实现线性回归以及多元回归
Apr 11 Python
七个非常实用的Python工具包总结
Jun 15 Python
详解python的异常捕获
Mar 03 Python
Python通用验证码识别OCR库ddddocr的安装使用教程
Jul 07 Python
Python爬虫爬取微博热搜保存为 Markdown 文件的源码
Feb 22 #Python
Python爬虫制作翻译程序的示例代码
Feb 22 #Python
Python爬虫爬取ts碎片视频+验证码登录功能
Feb 22 #Python
sklearn中的交叉验证的实现(Cross-Validation)
Feb 22 #Python
Python爬虫分析微博热搜关键词的实现代码
Feb 22 #Python
anaconda升级sklearn版本的实现方法
Feb 22 #Python
详解Python 中的 defaultdict 数据类型
Feb 22 #Python
You might like
用php+javascript实现二级级联菜单的制作
2008/05/06 PHP
两个DIV等高的JS的实现代码
2007/12/23 Javascript
JavaScript 学习笔记(十三)Dom创建表格
2010/01/21 Javascript
javascript 程序库的比较(一)之DOM功能
2010/04/07 Javascript
基于Jquery的仿照flash放大图片效果代码
2011/03/16 Javascript
使用jquery中height()方法获取各种高度大全
2014/04/02 Javascript
js 显示base64编码的二进制流网页图片
2014/04/04 Javascript
JQuery拖动表头边框线调整表格列宽效果代码
2014/09/10 Javascript
js实现iframe跨页面调用函数的方法
2014/12/13 Javascript
基于jQuery仿淘宝产品图片放大镜代码分享
2020/06/23 Javascript
JS数组排序技巧汇总(冒泡、sort、快速、希尔等排序)
2015/11/24 Javascript
jQuery事件的绑定、触发、及监听方法简单说明
2016/05/10 Javascript
jQuery配合coin-slider插件制作幻灯片效果的流程解析
2016/05/13 Javascript
JavaScript 数组- Array的方法总结(推荐)
2016/07/21 Javascript
AngularJS 入门教程之事件处理器详解
2016/08/19 Javascript
Javascript仿京东放大镜的效果
2017/03/01 Javascript
JavaScript中重名的函数与对象示例详析
2017/09/28 Javascript
js input输入百分号保存数据库失败的解决方法
2018/05/26 Javascript
layui前端框架之table表数据的刷新方法
2018/08/17 Javascript
移动端 Vue+Vant 的Uploader 实现上传、压缩、旋转图片功能
2019/06/10 Javascript
JavaScript canvas实现雪花随机动态飘落
2020/02/08 Javascript
在Webpack中用url-loader处理图片和字体的问题
2020/04/28 Javascript
Django自定义manage命令实例代码
2018/02/11 Python
Python3.5面向对象编程图文与实例详解
2019/04/24 Python
如何不用安装python就能在.NET里调用Python库
2019/07/12 Python
pytorch .detach() .detach_() 和 .data用于切断反向传播的实现
2019/12/27 Python
对python中arange()和linspace()的区别说明
2020/05/03 Python
Python如何实现爬取B站视频
2020/05/20 Python
使用python把xmind转换成excel测试用例的实现代码
2020/10/12 Python
2014年父亲节活动方案
2014/03/06 职场文书
助人为乐道德模范事迹材料
2014/08/16 职场文书
2014年团工作总结
2014/11/27 职场文书
python自动化调用百度api解决验证码
2021/04/13 Python
教你使用vscode 搭建react-native开发环境
2021/07/07 Javascript
python blinker 信号库
2022/05/04 Python
Python使用Beautiful Soup(BS4)库解析HTML和XML
2022/06/05 Python