我有以下url:https://tenhou.net/3/mjlog2xml.cgi?2009042400gm-00b9-0000-3a2a55dc
它只包含文本,我想下载它并使用Python将其作为xml文件存储在我的磁盘上。我正在使用requests模块。下面是我尝试做的事情:
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。
我使用requests方法收到的HTML是:
<html>
<body>
<p>PLEASE DOWNLOAD RAW FILE</p>
</body>
</html>>但是网站上的超文本标记语言是like this
我要下载的文本在左边。HTML显示在右侧。如果我能得到右边的超文本标记语言,那么我就知道如何使用像BeautifulSoup这样的东西来解析它并得到我想要的东西。但是我不确定为什么python-request和urllib没有给我正确的数据。
发布于 2019-12-27 12:07:00
该站点似乎会检查请求中发送的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)https://stackoverflow.com/questions/59495808
复制相似问题