requests.get()没有在python 2.7中检索正确的url

时间:2016-09-29 03:37:13

标签: macos python-2.7 python-requests

我尝试访问网址,然后根据标记解析内容。 我的代码:

page = requests.get('https://support.apple.com/downloads/')
self.tree = html.fromstring(page.content)
names = self.tree.xpath("//span[@class='truncate_name']//text()")

问题:变量页面包含url 'https://support.apple.com/'的数据 我是python 2.7的新手。文件中的整个编码问题。我使用unicode-escape作为默认编码。 https://support.apple.com/downloads/上的资源编码为utf-8,而https://support.apple.com/处的资源编码是可变的。这与问题有关吗?请为此提出解决方案。

1 个答案:

答案 0 :(得分:2)

它与编码无关,您正在寻找的是动态创建的,因此不会在您获得的源代码中。一系列ajax调用填充数据。要从您在浏览器中看到span.truncate_name的轮播中获取产品名称等..

params = {"page": "products",
          "locale": "en_US",
          "doctype": "DOWNLOADS",
          }
js = requests.get("https://km.support.apple.com/kb/index", params=params).content

通常我们可以在响应对象上调用 .json(),但在这种情况下我们需要使用"unicode_escape"然后调用加载

from json import loads, dumps
js2 = loads(js.decode("unicode_escape"))
print(js2)

这给你一个巨大的数据字典,如:

{u'products': [{u'name': u'Servers and Enterprise', u'urlpath': u'serversandenterprise', u'order': u'', u'products': .............

您可以在Chrome工具中看到请求:

enter image description here

我们要离开callback:ACDow‌​nloadSearch.customCa‌​llBack因为我们想要找回有效的json。