我们有时在对网站数据进行抓取的时候,返现页面源码内容只有写js代码,并没有数据,或者我们在一个页面点击下一页页面不会刷新,数据直接就出来了,这些都使用了ajax技术。
ajax详解:https://blog.csdn.net/DreamWeaver_zhou/article/details/76790588
Ajax对应特殊的请求类型:xhr,我们可以在浏览器的调试工具中进行筛选,我们使用python模拟ajax请求,可能返回的html,也可能是json类型的str数据,下面的例子都返回的是数据
实战:
1.虎牙直播数据抓取
首先我们得先来分析一下xhr文件,我们以chrome为例,来看一下,
点开lol直播,第一页的xhr文件,我们发现都看不懂,那就下一页来到第二页,我们还是看不懂,继续来到第三页,不出意外,我们还是看不懂,但是,请注意,有一条请求引起了我们的注意
在第二页和第三页,这个请求的地址发生了细微的变化,并且地址上的参数就是页数,这不禁引起了我们的思考,我们访问一下这个地址试试,
依然看不懂,但是他像不像一大串btyes类型json数据格式,我们取一小部分进行格式化个编码,
这不就是数据嘛,所以我们上边发现的那个url上承载着不同地址的数据,我们可以通过换page参数来获取数据
下来是代码
import requests
page = 1
headers = {
"Referer": "https://www.huya.com/g/lol",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36",
"x-requested-with": "XMLHttpRequest"
}
def sed_url(url):
response = requests.get(url=base_url, headers=headers)
return response
def parse_data(response):
ret = response.json()
datas = ret["data"]["datas"]
return datas
while 1:
if page <= 38:
base_url = 'https://www.huya.com/cache.php?m=LiveList&do=getLiveListByPage&gameId=1&tagAll=0&page={page}'.format(page=page)
response = sed_url(base_url)
datas = parse_data(response)
for data in datas:
print("主播", data["nick"], end=" ")
print("房间号", data["profileRoom"], end=" ")
print("简介", data["introduction"])
page += 1
else:
break
举一反三,下面还有个程序,按照爬取虎牙直播数据的流程进行分析
2.kfc地址抓取
import requests
page = 1
base_url = "http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname"
data = {
"cname": "北京",
"pid":"",
"pageIndex": page,
"pageSize": 10
}
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36",
"Referer":"kfc.com.cn"
}
while 1:
if page <= 10:
response = requests.post(url=base_url,data=data,headers=headers)
print(response.json())
tables = response.json()["Table1"]
for table in tables:
print(table)
page += 1
else:
break