Python2.7使用请求

时间:2016-11-15 14:30:18

标签: ajax python-2.7 python-requests firebug

如何使用python的请求获取此iframe的内容?

在Firebug中,iframe的内容来自POST请求的响应,我发现很难使用Python访问。

代码。

import requests

iframe_url = "https://wwwrs.resbank.co.za/BpsReports/InstNotice.aspx"

# How do I scrape the payload for the POST request?
r = requests.post(iframe_url) # data=?

r.text

回复。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head><title>Bank Institutions</title>...

我想要的回复。

1|#||4|224|updatePanel|ctl00_MainContent_ReportViewer1_DocMap|<div id="ctl00_MainContent_ReportViewer1_ctl09" style="display:none;">
<input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl09$ClientClickedId" id="ctl00_MainContent_ReportViewer1_ctl09_ClientClickedId" /></div>...

如何刮取POST请求的数据?

修改

我在POST请求中添加了浏览器标头和有效负载。响应看起来像我想要的(因为它是管道分隔的),但它没有显示iframe的内容。

附加代码 - 标头和有效负载。

headers = {
    'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1', 
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}

payload = {
    "ctl00$MainContent$ScriptManager1": "ctl00$MainContent$ScriptManager1|ctl00$MainContent$ReportViewer1$ctl10$Reserved_AsyncLoadTarget",
    "__EVENTTARGET": "ctl00$MainContent$ReportViewer1$ctl10$Reserved_AsyncLoadTarget",
    "__EVENTARGUMENT": "",
    "__VIEWSTATE":  
    "/wEPDwUKLTYyOTE1Njg2OQ9kFgJmD2QWA..." # shortened 
    "__VIEWSTATEGENERATOR": "E6F8CED1",
    "__EVENTVALIDATION":    
    "/wEdABKvYwmAyl699cXAjRyhDjs8urvg...", # shortened
    "ctl00$MainContent$ReportViewer1$ctl03$ctl11":"ltr",
    "ctl00$MainContent$ReportViewer1$ctl03$ctl12":"standards",
    #"ctl00$MainContent$ReportViewer1$AsyncWait$HiddenCancelField":"False",
    "ctl00$MainContent$ReportViewer1$ctlToggleParam$store":"false",
    #"ctl00$MainContent$ReportViewer1$ctl08$collapse":"false",
    "ctl00$MainContent$ReportViewer1$ctl10$VisibilityState$ctl00":None,
    #"ctl00$MainContent$ReportViewer1$ctl10$ReportControl$ctl04":100,
    "__ASYNCPOST": "true"
}

r = requests.post(url, headers=headers, data=payload, timeout=3.5)

有几个键没有值,一些键值对导致500服务器错误,所以我省略了它们并分别将它们注释掉了。

Python中的响应不包含iframe。

1|#||4|7645|updatePanel|ctl00_MainContent_ReportViewer1_ReportViewer|
  <div id="ctl00_MainContent_ReportViewer1" 
  onclick="if 
   ($get('ctl00_MainContent_ReportViewer1_ctl04') != null && 
    $get('ctl00_MainContent_ReportViewer1_ctl04').control != null) 
    $get('ctl00_MainContent_ReportViewer1_ctl04').control.HideActiveDropDown();" 
  onactivate="if
   ($get('ctl00_MainContent_ReportViewer1_ctl04') != null && 
    $get('ctl00_MainContent_ReportViewer1_ctl04').control != null) 
    $get('ctl00_MainContent_ReportViewer1_ctl04').control.HideActiveDropDown();" style="height:400px;width:400px;position:absolute;left:0px;Top:0px">
  <div id="ctl00_MainContent_ReportViewer1_HttpHandlerMissingErrorMessage" style="border-color:Red;border-width:2px;border-style:Solid;padding:10px;display:none;overflow:auto;font-size:.85em;">
   <h2>
      Report Viewer Configuration Error
   </h2><p>The Report Viewer Web Control HTTP Handler has not been registered in the application's web.config file.  
            Add <add verb="*" path="Reserved.ReportViewerWebControl.axd" 
            type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, 
            Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> to the system.web/httpHandlers section of the web.config file, or add <add 
            name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd"
            type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, 
            Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> to the system.webServer/handlers section for Internet Information Services 7 or later.
        </p>
  </div>
  <span id="ctl00_MainContent_ReportViewer1_ctl03">
    <input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl03$ctl00" id="ctl00_MainContent_ReportViewer1_ctl03_ctl00" />
    <input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl03$ctl01" id="ctl00_MainContent_ReportViewer1_ctl03_ctl01" />
  </span>
    <input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl11" id="ctl00_MainContent_ReportViewer1_ctl11" />
    <input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl12" id="ctl00_MainContent_ReportViewer1_ctl12" />
      <div id="ctl00_MainContent_ReportViewer1_AsyncWait" style="background-color:White;opacity:0.7;position:absolute;display:none;filter:alpha(opacity=70);">
      </div>
      <div id="ctl00_MainContent_ReportViewer1_AsyncWait_Wait" style="cursor:wait;background-color:#ECE9D8;padding:15px;border:1px solid black;display:none;position:absolute;">
        <table height="100%">
          <tr>
            <td width="32px" height="32px">
              <img src="/BpsReports/Reserved.ReportViewerWebControl.axd?OpType=Resource&Version=10.0.30319.1&Name=Microsoft.Reporting.WebForms.Icons.SpinningWheel.gif" style="height:32px;width:32px;" />
            </td>
            <td style="vertical-align:middle;text-align:center;">
              <span style="font-family:Verdana;font-size:14pt;">Loading...</span>
                <div style="margin-top:3px;">
                  <a href="javascript:$get('ctl00_MainContent_ReportViewer1_AsyncWait').control._cancelCurrentPostback();" style="font-family:Verdana;font-size:8pt;color:#3366CC;">Cancel</a>...

Firebug中的响应包含iframe。

1|#||4|224|updatePanel|ctl00_MainContent_ReportViewer1_DocMap|<div id="ctl00_MainContent_ReportViewer1_ctl09"
 style="display:none;">
    <input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl09$ClientClickedId" id="ctl00_MainContent_ReportViewer1_ctl09_ClientClickedId"
 />
</div>|5472|updatePanel|ctl00_MainContent_ReportViewer1_ctl10_ReportArea|<div NewContentType="Microsoft
.Reporting.WebFormsClient.ReportAreaContent.ReportPage" ForNonReportContentArea="false" id="ctl00_MainContent_ReportViewer1_ctl10_VisibilityState"
 style="visibility:none;">
    <input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl10$VisibilityState$ctl00" value="ReportPage"
 />
</div><input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl10$ScrollPosition" id="ctl00_MainContent_ReportViewer1_ctl10_ScrollPosition"
 /><span id="ctl00_MainContent_ReportViewer1_ctl10_Reserved_AsyncLoadTarget"></span><div id="ctl00_MainContent_ReportViewer1_ctl10_ReportControl"
 style="display:none;">
    <span></span><input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl10$ReportControl$ctl02" id
="ctl00_MainContent_ReportViewer1_ctl10_ReportControl_ctl02" /><input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl10$ReportControl$ctl03"
 id="ctl00_MainContent_ReportViewer1_ctl10_ReportControl_ctl03" /><input type="hidden" name="ctl00$MainContent$ReportViewer1$ctl10$ReportControl$ctl04"
 id="ctl00_MainContent_ReportViewer1_ctl10_ReportControl_ctl04" value="100" /><div style="display:none
;">
        <DIV dir=...The content of the iframe.

可能有助于解决方案的问题。

  1. 如何为POST请求刮取有效负载?

  2. 准备有效负载的请求序列是?

  3. 如何通过请求获取iframe?

  4. 感谢阅读。

1 个答案:

答案 0 :(得分:1)

如果抓取Cookie然后将其添加到标题中,则可以使用iframe的内容。

headers = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'}

r = requests.get(url)
cookie = {'Cookie': r.headers['Set-Cookie']}
headers.update(cookie)

可以通过删除没有值的密钥来缩短有效负载,例如__EVENTARGUMENT。

payload = {
    "__EVENTTARGET": "ctl00$MainContent$ReportViewer1$ctl10$Reserved_AsyncLoadTarget",
    "__VIEWSTATE": "/wEPDwUKLTYyOTE1Njg2OQ9kFgJmD2...", # shortened
    "__EVENTVALIDATION": "/wEdABKvYwmAyl699cXAjRyh...", # shortened
    "__ASYNCPOST": "true"
}

iframe(URL)的内容可以存储在列表中。

from bs4 import BeautifulSoup
soup = BeautifulSoup(r.text)
links = soup.table.find_all('a')
hrefs = [ i['href'] for i in links ]

>>>['https://wwwrs.resbank.co.za/BpsReports/bankContactRprtPage.**Edit.**aspx?Code=BL', 'https://wwwrs.resbank.co.za/BpsReports/bankContactRprtPage.aspx?Code=BR', 'https://wwwrs.resbank.co.za/BpsReports/bankContactRprtPage.aspx?Code=R', 'https://wwwrs.resbank.co.za/BpsReports/bankContactRprtPage.aspx?Code=FB', 'https://wwwrs.resbank.co.za/BpsReports/bankContactRprtPage.aspx?Code=LB', 'https://wwwrs.resbank.co.za/BpsReports/bankContactRprtPage.aspx?Code=MB']

<强>更新

这个答案在很短的时间后失败了。我认为这是因为参数__VIEWSTATE和__ EVENTVALIDATION都会在每个会话中发生变化,因此需要将其删除而不是硬编码到程序中。

更新了解决方案

由于某些变量过期,下面更新的解决方案会在每次运行时删除新参数。它们是:Cookie,__ ReviewSTATE和__EVENTVALIDATION。现在这是一个有效的解决方案。

import requests
from bs4 import BeautifulSoup
import re

url = "https://wwwrs.resbank.co.za/BpsReports/InstNotice.aspx"

r = requests.get(url)

headers = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) '\
    + 'Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'}

cookie = {'Cookie': r.headers['Set-Cookie']}
headers.update(cookie)

payload = {
    '__EVENTTARGET': 'ctl00$MainContent$ReportViewer1$ctl10$Reserved_AsyncLoadTarget',
    '__ASYNCPOST': 'true'
}

view_state = re.search(r'__VIEWSTATE"\svalue="(.*)"', r.text)
payload['__VIEWSTATE'] = str(view_state.group(1)) 
# request docs advise str over unicode for header values.

event_validation = re.search(r'__EVENTVALIDATION"\svalue="(.*)"', r.text)
payload['__EVENTVALIDATION'] = str(event_validation.group(1))

r = requests.post(url, headers=headers, data=payload, timeout=3.5)

soup = BeautifulSoup(r.text)
links = soup.table.find_all('a')
hrefs = [ i['href'] for i in links ]