【问题标题】:How can I access this type of site using requests? [duplicate]如何使用请求访问此类站点? [复制]
【发布时间】:2020-10-02 20:25:23
【问题描述】:

这是我第一次遇到一个“不允许我访问”网页的网站。我不知道为什么,也不知道如何从这个网站上抓取。

我的尝试:

import requests
from bs4 import BeautifulSoup

def html(url):
    return BeautifulSoup(requests.get(url).content, "lxml")

url = "https://www.g2a.com/"

soup = html(url)

print(soup.prettify())

输出:

<html>
 <head>
  <title>       
   Access Denied
  </title>
 </head>
 <body>
  <h1>
   Access Denied
  </h1>
  You don't have permission to access "http://www.g2a.com/" on this server.
  <p>
   Reference #18.4d24db17.1592006766.55d2bc1
  </p>
 </body>
</html>

我已经研究了一段时间,发现应该有某种类型的token [访问、刷新等...]。

还有,action="/search",但我不知道该怎么办。

【问题讨论】:

标签: python web-scraping python-requests


【解决方案1】:

这个页面需要指定一些HTTP头来获取信息(Accept-Language):

import requests
from bs4 import BeautifulSoup

headers = {'Accept-Language': 'en-US,en;q=0.5'}

def html(url):
    return BeautifulSoup(requests.get(url, headers=headers).content, "lxml")

url = "https://www.g2a.com/"

soup = html(url)

print(soup.prettify())

打印:

<!DOCTYPE html>
<html lang="en-us">
 <head>
  <link href="polyfill.g2a.com" rel="dns-prefetch"/>
  <link href="images.g2a.com" rel="dns-prefetch"/>
  <link href="id.g2a.com" rel="dns-prefetch"/>
  <link href="plus.g2a.com" rel="dns-prefetch"/>

... and so on.

【讨论】:

  • 在这种情况下是否有多个标题可以使用?如果没有,你怎么知道哪个标头可以工作?
  • @thehammerons 在我的情况下,仅指定 Accept-Language 有效,但如果它不适合您,您可以尝试 User-Agent 等。查看 Firefox 开发人员工具了解更多信息(Chrome 有类似的东西)。
猜你喜欢
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
  • 2019-04-02
  • 1970-01-01
  • 2021-04-09
相关资源
最近更新 更多