【问题标题】:Python requests not respondingPython 请求没有响应
【发布时间】:2016-03-30 07:58:38
【问题描述】:

做了几个成功的小项目,多年来一直在努力从这个网站获得请求 - 有什么建议吗?

更新 - 想要获得完整的美味汤请求,以便我可以开始从表格中抓取信息

from bs4 import BeautifulSoup
import requests

r = requests.get("http://www.transfermarkt.co.uk/championship/marktwerte/wettbewerb/GB2")
soup = BeautifulSoup(r.content,"html.parser")
print soup

返回

<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</hr></body>
</html>

【问题讨论】:

  • 你希望它返回什么? (更新您的问题!)(欢迎来到 SO!)

标签: python beautifulsoup python-requests


【解决方案1】:

您需要假装是浏览器的真实用户并提供User-Agent 标头:

r = requests.get("http://www.transfermarkt.co.uk/championship/marktwerte/wettbewerb/GB2", headers={
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"
})

演示:

>>> from bs4 import BeautifulSoup
>>> import requests
>>> 
>>> r = requests.get("http://www.transfermarkt.co.uk/championship/marktwerte/wettbewerb/GB2", headers={
...     "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"
... })
>>> soup = BeautifulSoup(r.content,"html.parser")
>>> print(soup.title.get_text())
Top market values 15/16 - Championship - Transfermarkt

【讨论】:

  • 非常好,非常感谢您向我介绍用户代理 - 很快就会标记为已解决
  • 不错..用胡须打败我!
  • 我在同一个网站上遇到了完全相同的问题,我提供什么样的用户代理有关系吗?
  • 如果您仍然面临同样的问题,请查看此帖子stackoverflow.com/questions/51154114/…
【解决方案2】:

有些网站的请求无法给出响应,因为其中许多网站会跟踪请求发起方是浏览器还是机器人。 所以,让我们看起来像一个浏览器。
可以通过如下修改表头来完成:

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36', "Upgrade-Insecure-Requests": "1","DNT": "1","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language": "en-US,en;q=0.5","Accept-Encoding": "gzip, deflate"}

然后,只需将这个标头添加到您的 GET 请求中,如下所示:

response = requests.get("https://example.com",headers=headers)

总共你会得到:

import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36', "Upgrade-Insecure-Requests": "1","DNT": "1","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language": "en-US,en;q=0.5","Accept-Encoding": "gzip, deflate"}
response = requests.get("https://example.com",headers=headers)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多