无法从请求python获取完整表

时间:2018-09-30 22:57:19

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

我正在尝试从以下网站获取整个表格:https://br.investing.com/commodities/aluminum-historical-data

但是当我发送此代码时:

with requests.Session() as s:
r = s.post('https://br.investing.com/commodities/aluminum-historical-data',
                 headers={"curr_id": "49768","smlID": "300586","header": "Alumínio Futuros Dados Históricos",
                          'User-Agent': 'Mozilla/5.0', 'st_date': '01/01/2017','end_date': '29/09/2018',
                         'interval_sec': 'Daily','sort_col': 'date','sort_ord': 'DESC','action': 'historical_data'})

bs2 = BeautifulSoup(r.text,'lxml')
tb = bs2.find('table',{"id":"curr_table"})

它仅返回表格的一部分,而不是我刚刚过滤的整个日期。

我确实看到了以下帖子页面:

enter image description here

有人可以帮我获取刚刚过滤的整个表格吗?

2 个答案:

答案 0 :(得分:0)

问题是您要以 headers 形式从 data 传递。

您必须在data中使用带有关键字request.Session.post的数据发送数据:

with requests.Session() as session:

    url = 'https://br.investing.com/commodities/aluminum-historical-data'

    data = {
        "curr_id": "49768",
        "smlID": "300586",
        "header": "Alumínio Futuros Dados Históricos",
        'User-Agent': 'Mozilla/5.0',
        'st_date': '01/01/2017',
        'end_date': '29/09/2018',
        'interval_sec': 'Daily',
        'sort_col': 'date',
        'sort_ord': 'DESC',
        'action': 'historical_data',
        }

    your_headers = {}  # your headers here

    response = session.post(url, data=data, headers=your_headers)

bs2 = BeautifulSoup(response.text,'lxml')
tb = bs2.find('table',{"id":"curr_table"})

我还建议您在POST请求中包括您的标头(尤其是user-agents),因为该网站不允许使用漫游器。在这种情况下,如果这样做,将很难检测到该机器人。

答案 1 :(得分:0)

您在代码中犯了两个错误。

第一个是网址。 您需要使用正确的url才能向investing.com请求数据。 您当前的url'https://br.investing.com/commodities/aluminum-historical-data'

但是,当您看到检查并单击'Network'时,Request URLhttps://br.investing.com/instruments/HistoricalDataAjax

您的第二个错误存在于s.post(blah)中。如上面的Federico Rubbi所述,您分配给headers的代码必须分配给data

现在,您的错误已全部解决。您只需要再执行一步即可。您必须向{'X-Requested-With': 'XMLHttpRequest'}添加字典your_headers。从您的代码中可以看到,您已经在Network tab中检查了HTML inspection。因此,您大概就能知道为什么需要{'X-Requested-With': 'XMLHttpRequest'}

因此整个代码应如下所示。

import requests
import bs4 as bs

with requests.Session() as s:
    url = 'https://br.investing.com/instruments/HistoricalDataAjax' # Making up for the first mistake.
    your_headers = {'User-Agent': 'Mozilla/5.0'}

    s.get(url, headers= your_headers)
    c_list = s.cookies.get_dict().items()
    cookie_list = [key+'='+value for key,value in c_list]
    cookie = ','.join(cookie_list)

    your_headers = {**{'X-Requested-With': 'XMLHttpRequest'},**your_headers}
    your_headers['Cookie'] = cookie

    data= {} # Your data. Making up for the second mistake.

    response = s.post(url, data= data, headers = your_headers)