爬虫 处理网页中的ajax请求

浏览器:Google Chrome

Python版本:3.7

所引用的库

from collections import deque
import requests
import json
from bs4 import BeautifulSoup
import re

解决步骤

  1. 按F12查看需要爬取的网页源代码,点击Network中的XHR,可以看到在Name文件列表找到对应文件。
    爬虫 处理网页中的ajax请求
  2. 单击该文件,点击Headers,可以发现网站其实是向https://www.taptap.com/ajax/top/download?page=2&total=30发出了GET请求。
    爬虫 处理网页中的ajax请求
    再往下拉可以看到请求的参数为page和total:
    爬虫 处理网页中的ajax请求
  3. 根据获取到的信息设置初始参数
total = 30
page = 2
json_url = 'https://www.taptap.com/ajax/top/download?total=' + str(total) + '&page=' + str(page)
unvisited = deque()     # 待爬取的链接的集合,使用广度优先搜索
visited = set()         # 已访问的链接集合
unvisited.append(json_url)
  1. 解析从网页获取到的内容,并且根据字典的结构获取到html代码
    爬虫 处理网页中的ajax请求
r = requests.get(json_url).text     # 在返回一个Response对象后,通过.text获取网页的内容
data = json.loads(r)                # 将json格式数据转换为字典
data = data['data']					
htmlCode = data['html']

5.爬虫主体

print('--开始爬取--')
count = 0       # 爬取页面的数量编号
while unvisited:
    url = unvisited.popleft()
    visited.add(url)
    count += 1
    print('开始抓取第', count, '个链接:', url)

    soup = BeautifulSoup(htmlCode, 'lxml')
    all_a = soup.find_all('a', {'class': "card-middle-title"})		# 查找页面中所有链接
    for a in all_a:
        x = a.attrs['href']  # 获取网址
        if re.match(r'https.+', x):		# 使用正则表达式筛选出符合条件的内容
            if not re.match(r'https://www.taptap.com/app/.+?', x):
                continue
        if (x not in visited) and (x not in unvisited):
            unvisited.append(x)

6.运行结果
爬虫 处理网页中的ajax请求