2017-04-23 181 views
1

我嘗試使用Python請求上的RSS源。在過去,我使用過urllib,或者要求庫來達到這個目的,並且它工作的很好。但是這一次,我繼續獲得406 status error,我知道該頁面告訴我它不接受請求中的頭部詳細信息。我嘗試改變它,但無濟於事。
這就是我試過我如何請求(獲取)並使用python讀取xml文件?

import requests 
url = 'https://www.treasurydirect.gov/TA_WS/securities/announced/rss' 
user_agent = {'User-agent': 'Mozilla/5.0'} 
response = requests.get(url, headers = user_agent) 
print response.text 

環境:的Python 2.7和3.4。 我也嘗試通過curl訪問相同的確切錯誤。

我認爲這是頁面特定的,但無法弄清楚如何適當地構建請求來閱讀此頁面。

我在頁面上發現了一個API,我可以在json中讀取相同的數據,所以這個問題現在更多的是對我的好奇心,而不是真正的問題。

任何答案將不勝感激!

標題詳細

{'surrogate-control': 'content="ESI/1.0",no-store', 'content-language': 'en-US', 'x-content-type-options': 'nosniff', 'x-powered-by': 'Servlet/3.0', 'transfer-encoding': 'chunked', 'set-cookie': 'BIGipServerpl_www.treasurydirect.gov_443=3221581322.47873.0000; path=/; Httponly; Secure, TS01598982=016b0e6f4634928e3e7e689fa438848df043a46cb4aa96f235b0190439b1d07550484963354d8ef442c9a3eb647175602535b52f3823e209341b1cba0236e4845955f0cdcf; Path=/', 'strict-transport-security': 'max-age=31536000; includeSubDomains', 'keep-alive': 'timeout=10, max=100', 'connection': 'Keep-Alive', 'cache-control': 'no-store', 'date': 'Sun, 23 Apr 2017 04:13:00 GMT', 'x-frame-options': 'SAMEORIGIN', '$wsep': '', 'content-type': 'text/html;charset=ISO-8859-1'} 

回答

1

您需要添加accept到頁眉請求:

import requests 

url = 'https://www.treasurydirect.gov/TA_WS/securities/announced/rss' 
headers = {'accept': 'application/xml;q=0.9, */*;q=0.8'} 
response = requests.get(url, headers=headers) 

print response.text 
+0

完美。謝謝! – Dom

+0

不客氣!我很高興能夠提供幫助。 – vold