【问题标题】:Requests does not return html anymore - Python请求不再返回 html - Python
【发布时间】:2015-04-19 13:47:31
【问题描述】:

我正在尝试通过 python 请求 (2.7) 从公共 Linkedin url 获取名称。

以前的代码可以正常工作。

import requests
from bs4 import BeautifulSoup

url = "https://www.linkedin.com/in/linustorvalds"
html = requests.get(url).content

link = BeautifulSoup(html).title.text.split("|")[0].replace(" ","")
print link

想要的输出是:

linustorvalds

我收到以下错误消息:

AttributeError: 'NoneType' object has no attribute 'text'

问题似乎是 html 没有返回页面的真实内容。所以没有找到“标题”。这是打印html的结果:

<html><head>
<script type="text/javascript">
window.onload = function() {
  var newLocation = "";
  if (window.location.protocol == "http:") {
    var cookies = document.cookie.split("; ");
    for (var i = 0; i < cookies.length; ++i) {
      if ((cookies[i].indexOf("sl=") == 0) && (cookies[i].length > 3)) {
        newLocation = "https:" + window.location.href.substring(window.location.protocol.length);
      }
    }
  }

  if (newLocation.length == 0) {
    var domain = location.host;
    var newDomainIndex = 0;
    if (domain.substr(0, 6) == "touch.") {
      newDomainIndex = 6;
    }
    else if (domain.substr(0, 7) == "tablet.") {
      newDomainIndex = 7;
    }
    if (newDomainIndex) {
      domain = domain.substr(newDomainIndex);
    }
    newLocation = "https://" + domain +  "/uas/login?trk=sentinel_org_block&session_redirect=" + encodeURIComponent(window.location)
  }
  window.location.href = newLocation;
}
</script>
</head></html>

我被屏蔽了吗?有什么建议可以让这段代码像以前一样工作?

非常感谢!

【问题讨论】:

  • 那里的 Javascript 试图重定向用户 -- window.location.href = newLocation。您可能需要遵循该重定向。

标签: python html beautifulsoup python-requests


【解决方案1】:

尝试设置一个 User-Agent 标头:

html = requests.get(url, headers={"User-Agent": "Requests"}).content

【讨论】:

  • 像冠军一样工作!!非常感谢!!
  • 为什么我们需要设置标题?
  • @AvinashRaj 我不知道。我们可能不得不问Linkedin:D
  • @AvinashRaj 因为 LinkedIn 有一个专门用于从他们的服务中检索数据的 API,并且他们会尽一切努力阻止人们抓取他们网站的 HTML 版本。在您开始使用 API 之前,您将不断遇到这种情况,因为他们会不断更新其反抓取工作,而这只会持续很长时间。
猜你喜欢
  • 2016-04-14
  • 1970-01-01
  • 2022-10-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多