python - 使用 PostBack 数据 javascript url 抓取页面的 Scrapy 不会改变
问题描述
我正在通过 Scrapy 使用 ASP.NET 编程浏览一些目录。
要爬网的页面编码如下:
javascript:__doPostBack('MoreInfoListZbgs1$Pager','X')
其中 X 是 1 到 180 之间的整数。问题是当我单击下一页或任何页面时,url 保持不变。我在下面写了一些代码,这些代码只能提取第一页中的每个链接。
# -*- coding: utf-8 -*-
import scrapy
from bs4 import BeautifulSoup
import re
from scrapy.http import FormRequest
import js2xml
import requests
from datetime import datetime
class nnggzySpider(scrapy.Spider):
name = 'nnggzygov'
start_urls = [
'https://www.nnggzy.org.cn/gxnnzbw/showinfo/zbxxmore.aspx?categorynum=001004001'
]
base_url = 'https://www.nnggzy.org.cn'
custom_settings = {
'LOG_LEVEL': 'ERROR'
}
def parse(self, response):
_response = response.text
self.data = {}
soup = BeautifulSoup(response.body, 'html.parser')
tags = soup.find_all('a', href=re.compile(r"InfoDetail"))
# 获取翻页参数
__VIEWSTATE = re.findall(r'id="__VIEWSTATE" value="(.*?)" />', _response)
A = __VIEWSTATE[0]
# print(A)
__EVENTTARGET = 'MoreInfoListZbgs1$Pager'
B = __EVENTTARGET
__CSRFTOKEN = re.findall(r'id="__CSRFTOKEN" value="(.*?)" />', _response)
C = __CSRFTOKEN
page_num = re.findall(r'title="转到第(.*?)页"', _response)
max_page = page_num[-1]
content = {
'__VIEWSTATE': A,
'__EVENTTARGET': B,
'__CSRFTOKEN': C,
'page_num': max_page
}
infoid = re.findall(r'InfoID=(.*?)&CategoryNum', _response)
print(infoid)
yield scrapy.Request(url=response.url, callback=self.parse_detail, meta={"data": content})
def parse_detail(self, response):
max_page = response.meta['data']['page_num']
for i in range(2, int(max_page)):
data = {
'__CSRFTOKEN': '{}'.format(response.meta['data']['__CSRFTOKEN']),
'__VIEWSTATE': '{}'.format(response.meta['data']['__VIEWSTATE']),
'__EVENTTARGET': 'MoreInfoListZbgs1$Pager',
'__EVENTARGUMENT': '{}'.format(i),
# '__VIEWSTATEENCRYPTED': '',
# 'txtKey': ''
}
yield scrapy.FormRequest(url=response.url, callback=self.parse, formdata=data, method="POST", dont_filter=True)
谁能帮我这个?
解决方案
看起来上述网站的分页是通过发送带有 formdata 的 POST 请求来完成的,例如:
{
"__CSRFTOKEN": ...,
"__VIEWSTATE": ...,
"__EVENTTARGET": "MoreInfoListZbgs1$Pager",
"__EVENTARGUMENT": page_number,
"__VIEWSTATEENCRYPTED": "",
"txtKey": ""
}
推荐阅读
- nuxt.js - Nuxt PWA 注册服务工作者未在本地主机外部注册
- javascript - 在聊天 discordjs 之间复制嵌入和修改
- tensorflow - Tensorflow 中的 SGD 是否对每个数据点进行移动?
- android - api 仅适用于邮递员,而不是更改数据库列名称后的应用程序
- html - 如何使 inline-flex div 继承其最后一个孩子的宽度
- javascript - node-telegram-bot-api 中的消息延迟
- flutter - 在没有默认构造函数的情况下初始化一个空安全变量?
- jquery - .hide()/.show() 旁边是否有隐藏/显示元素的 jQuery 方法?
- laravel - Laravel 项目因 Datatables.net 构建问题而停止构建
- r - ggplot2美学中计算统计和变量的算术