python - 抓取需要 JavaScript 交互的页面

标签 python scrapy

我正在尝试抓取https://a836-propertyportal.nyc.gov/Default.aspx与 Scrapy 一起。我在使用 FormRequest 时遇到困难——具体来说,我不知道如何告诉 Scrapy 如何填写 block 和批处理表单,然后获取页面的响应。我尝试遵循此处找到的 Scrapy 网站上的 FormRequest 示例 ( http://doc.scrapy.org/en/latest/topics/request-response.html#using-formrequest-from-response-to-simulate-a-user-login ),但在正确单击“搜索”按钮时仍然遇到困难。

如果您能提供任何建议,以便我可以从提交的页面中提取数据,我将不胜感激。 SO 上的一些发帖者建议 Scrapy 不能很好地处理 JS 事件,而应该使用其他库,例如 CasperJS。

更新:如果有人可以向我指出一个允许我提交表单并检索后续信息的 Java/Python/JS 库,我将非常感激

更新的代码(根据 Pawel 的评论):我的代码可以在这里找到:

from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.http import FormRequest, Request

class MonshtarSpider(Spider):
name = "monshtar"
allowed_domains = ["https://a836-propertyportal.nyc.gov/Default.aspx"]
start_urls = (
    'https://a836-propertyportal.nyc.gov/Default.aspx/',
    )

def parse(self, response):
    print "entered the parsing section!!"

    yield Request("https://a836-propertyportal.nyc.gov/ExemptionDetails.aspx", 
        cookies = {"borough":"1", "block":"01000", "style":"default", "lot":"0011"}, callback = self.aftersubmit)


def aftersubmit(self, response):
    #get the data....
    print "SUCCESS!!\n\n\n"

最佳答案

您的页面有点奇怪且难以解析,在提交有效的 POST 请求后,页面会响应 302 http 状态和一堆 cookie(顺便说一句,您的表单数据无效,您需要将参数中的下划线替换为美元)。

发送GET到https://a836-propertyportal.nyc.gov/ExemptionDetails.aspx后即可查看内容

最令人惊讶的是,您可以仅使用 cookie 来抓取该网站,而无需 POST 请求。 POST 只是为您提供 cookie,它不会重定向到 html 响应或以 html 响应进行响应。您可以从您的蜘蛛中操纵这些 cookie。您只需要先进行 GET 即可获取 session cookie,然后连续进行带有行政区、区 block 等的 GETS。

在 scrapy shell 中尝试一下:

pawel@stackoverflow:~/stack/scrapy$ scrapy shell "https://a836-propertyportal.nyc.gov/Default.aspx"

In [1]: from scrapy.http import Request

In [2]: req = Request("https://a836-propertyportal.nyc.gov/ExemptionDetails.aspx", cookies = {"borough":"1", "block":"01000", "style":"default", "lot":"0011"})

In [3]: fetch(req)

In [4]: view(response)

Out[5]: True # opening browser window

此时的响应将包含给定街区、行政区和地 block 的特性数据。现在您只需在您的蜘蛛中使用这些知识即可。只需将您的 POST 替换为带有 cookies 的 GET,将回调添加到 shell 中,它应该可以正常工作。

如果这仍然不起作用或者在某种程度上不适合您的目的,请尝试提取隐藏的ajax参数(nullctl00_ScriptManager1_HiddenField的值),将其添加到formdata中(当然还要更正您的formdata,以便它与浏览器发送的内容相同)。

关于python - 抓取需要 JavaScript 交互的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23857535/

相关文章:

python - 列出 'minus' 项

javascript - (Python) Scrapy - 如何抓取 JS 下拉列表?

python - scrapy 仅抓取网站的一级

python - 查找路径的根

python - flask-sqlalchemy 对特定表使用 drop_all 和 create_all

python - 动态更改 scrapy 请求调度程序优先级

python - 设置 Scrapy 框架以在 Python 2.7 上运行

curl - Scrapy VS wget VS curl

python - 修改 Python 3.1 中的特定数组元素

python - Python 3 中的 super() 是如何实现的?