无法通过请求访问AJAX网址,BeautifulSoup

时间:2015-08-05 11:18:44

标签: python ajax web-scraping beautifulsoup python-requests

我正在尝试读取表的数据,这是以下webpage

的onclick ajax事件

如果您点击页面底部Tabelas选项卡右侧的+号,则会启动该事件。

从我的浏览器中使用FireBug(例如)y可以从NET部分的XHR选项卡中获取ajax 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,我可以看到该表,这是源代码。

我不知道我是否遗漏了某些内容,或者该页面本身阻止了任何直接的readinig尝试。

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

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

因为de属性类'find'什么都找不到。

我希望得到任何帮助和指导来解决这个障碍。

1 个答案:

答案 0 :(得分:0)

如果您检查 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