我有以下网址:https://tenhou.net/3/mjlog2xml.cgi?2009042400gm-00b9-0000-3a2a55dc
它仅包含文本,我想使用Python下载并将其作为xml文件存储在磁盘上。我正在使用请求模块。这是我尝试做的事情:
import requests
url = "https://tenhou.net/3/mjlog2xml.cgi?2009042400gm-00b9-0000-3a2a55dc"
r = requests.get(url, allow_redirects=True)
open('test.xml', 'wb').write(r.content)
当我检查test.xml
的内容时,它仅包含文本“请下载原始文件”。我也尝试使用urllib.request.urlopen()
,但得到的结果相同。
但是,当我在浏览器中打开url时,会看到完整的标记文本,甚至可以下载该页面并将其另存为xml。
我使用请求方法接收的HTML是:
<html>
<body>
<p>PLEASE DOWNLOAD RAW FILE</p>
</body>
</html>>
但是网站上的HTML是like this
我要下载的文本在左侧。 HTML显示在右侧。如果我能得到正确的HTML,那么我知道如何使用BeautifulSoup之类的东西来解析它并得到我想要的东西。但是我不确定为什么python-requests和urllib没有给我正确的数据。
答案 0 :(得分:1)
该站点似乎正在检查请求中发送的user-agent。
如果您在请求中明确设置了类似浏览器的用户代理,则会得到您尝试获取的响应:
import requests
url = "https://tenhou.net/3/mjlog2xml.cgi?2009042400gm-00b9-0000-3a2a55dc"
# Create a dictionary of the headers including the User-Agent
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
}
r = requests.get(url, headers=headers, allow_redirects=True)
open('test.xml', 'wb').write(r.content)