【问题标题】:Unable to access AJAX url with requests, BeautifulSoup无法通过请求访问 AJAX url,BeautifulSoup
【发布时间】:2015-08-05 11:18:43
【问题描述】:

我正在尝试读取一个表的数据,这是一个如下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 粘贴到浏览器中,我可以看到源代码中的表格。

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

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

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

因为属性类 'find' 什么也没找到。

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 哇!多谢!!!知道cookies,但没有考虑过post 变量。非常感谢您的帮助。
    猜你喜欢
    • 2012-05-24
    • 2019-06-11
    • 2015-12-20
    • 1970-01-01
    • 2019-07-11
    • 2019-02-20
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多