无法通过请求访问 AJAX url,BeautifulSoup

Unable to access AJAX url with requests, BeautifulSoup

我正在尝试读取 table 的数据,它是以下 webpage

的 onclick ajax 事件

如果您单击页面底部 Tabelas 选项卡右侧的 + 号,事件将启动。

在我的浏览器中使用 FireBug(例如),您可以从 NET 部分的 XHR 选项卡中选择 ajax url。

url有效,浏览器拾取并显示。

我的脚本:

 import requests

 urls="http://www.hidrografico.pt/components/com_products/scripts/server/data_getestactable.php"

 headers = {
'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
 }

 s = requests.Session()
 s.post(urls)

 content = s.post(urls, headers=headers)

 print content.content

此输出给出:

Direct access to this file is prohibited.

因此似乎无法直接访问 url,但如果我在浏览器中粘贴 url,我可以看到源代码中的 table。

我不知道是我遗漏了什么,还是页面本身阻止了任何直接阅读尝试。

我尝试通过主网页访问 table 使用 BeautifulSoup(text) 然后 blabla.find(class,{'id':blabla }) 然后 blabla.findAll() 但它返回

AttributeError: 'NoneType' object has no attribute 'findAll'

因为 de attribute class 'find' 什么也没找到。

如果能提供任何帮助和指导来解决这个问题,我将不胜感激。

如果您检查 POST 参数,您会发现您需要发送 estid=4&param=1 并且这只有在您拥有正确的 cookie 时才有效您可以通过向首页发送 GET 请求来获取。

import requests


# Prepare the session that will store the cookies.
s = requests.Session()
# Get the cookies
s.get("http://www.hidrografico.pt/boias-ondografo.php")

table_url = "http://www.hidrografico.pt/components/com_products/scripts/server/data_getestactable.php"    
# Prepare the parameters
payload = { "estid": "4",
        "param": "1" 
        }
r = s.post(table_url, data=payload)
print r.text