Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题
作者:程序猿小白^ 发布时间:2022-06-09 20:07:37
我们在编写Python爬虫时,有时会遇到网站拒绝访问等反爬手段,比如这么我们想爬取蚂蚁短租数据,它则会提示“当前访问疑似黑客攻击,已被网站管理员设置为拦截”提示,如下图所示。此时我们需要采用设置Cookie来进行爬取,下面我们进行详细介绍。非常感谢我的学生承峰提供的思想,后浪推前浪啊!
一. 网站分析与爬虫拦截
当我们打开蚂蚁短租搜索贵阳市,反馈如下图所示结果。
我们可以看到短租房信息呈现一定规律分布,如下图所示,这也是我们要爬取的信息。
通过浏览器审查元素,我们可以看到需要爬取每条租房信息都位于<dd></dd>节点下。
很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!
QQ群:810735403
在定位房屋名称,如下图所示,位于<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
#爬虫函数
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
接下来我们想获取详细信息
这里作者主要是提供分析Cookie的方法,使用浏览器打开网页,右键“检查”,然后再刷新网页。在“NetWork”中找到网页并点击,在弹出来的Headers中就隐藏这这些信息。
最常见的两个参数是Cookie和User-Agent,如下图所示:
然后在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文件:
同时,大家可以尝试Selenium爬取蚂蚁短租,应该也是可行的方法。
来源:https://blog.csdn.net/weixin_46737755/article/details/113859080
猜你喜欢
- 实例一--爬取页面import requestsurl="https//itemjd.com/2646846.html"
- matplotlib是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图。而且也
- Python中Math库和Python库都具备求对数的函数。import numpy as npimport math1. Numpy库1.
- 假设现有一张人员表(表名:Person),若想将姓名、身份证号、住址这三个字段完全相同的记录查找出来,使用1: SELECT p
- 如下所示:l = [1, 2, 3, 5]l_one = [2, 8, 6, 10]print set(l) & set(l_one
- 编写Python代码,大家都需要遵循PEP8,因此在pycharm中,如何设置每行最大长度限制,成为了一个小的知识盲点,在这里做一下记录,方
- 学习目的: 学习ADO.NET用法,并如何用DataRearder读取数据 今天练习数据库的最基本用法,如何打开数据库。首先在网站设置文件w
- 本文实例讲述了Python设计模式之MVC模式。分享给大家供大家参考,具体如下:一.简单介绍mvc模式 the mo
- 多个Python版本:在同一台机器上安装不同的Python,例如2.7和3.4。虚拟环境:独立的环境,既可以同时安装特定版本的Python,
- # 贪婪模式 默认的匹配规则# 在满足条件的情况下 尽可能多的去匹配到字符串import rers = re.match('\d{6
- 在这之前我们先回顾以前用php导出excel,我直接写成方法在这里:public static function phpExcelList(
- 一. XSL入门1.XSL---XML的样式表 HTML网页使用预先确定的标识(tags),这就是说所有的标记都有明确的含义,例如<p
- 在用python的bottle框架开发时,前端使用ajax跨域访问时,js代码老是进入不了success,而是进入了error,而返回的状态
- 高性能异步爬虫目的:在爬虫中使用异步实现高性能的数据爬取操作异步爬虫的方式:- 多线程、多进程(不建议):好处:可以为相关阻塞的操作单独开启
- 比较好奇python对于多进程中copy on write机制的实际使用情况。目前从实验结果来看,python 使用multiprocess
- 导语无论家用电脑还是公司的电脑,定时开关机都是一个非常实用的功能,只是一般都不太受关注。定时关机不仅能延长电脑的使用寿命,还能节约超多的电费
- 在国外一博客看到的技巧,终于解决IE的这个老大难问题。我在IE的setAttribute bug也提到其解决方法,一是innerHTML,一
- 如下所示:' '.join(line.split())例如:'line dd',运行line.split()
- 引文之前将PHP反序列化的基础知识讲了一遍,不知道大家学习的怎么样了,今天给大家带来PHP反序列化的进阶知识:PHAR反序列化,也是之前本人
- 目录一、前言二、基础命令三、正常显示中文:四、设置图样或子图五、设置x轴或y轴相关属性:六、设置标题:七、设置图例:八、进行标注:九、保存图