【问题标题】:Python BS4 not allowed to access the web pagePython BS4 不允许访问网页
【发布时间】:2021-11-08 21:22:56
【问题描述】:

首先我使用 html_doc=requests.get(x) 来阅读页面,但是当我打印汤时,我得到了 403 Forbidden 错误。

为了绕过这个,我添加了一个用户代理并使用了以下代码:html_doc=requests.get(x, headers=header) 但是,这一次,当我尝试打印汤时,我收到了 400 Bad Request 错误。

有人可以指导我并帮助找到解决此问题的方法吗?

编辑 - 代码:

from bs4 import BeautifulSoup, NavigableString
from urllib import request
import requests
import lxml
from lxml import etree
from lxml import html
x='https://www.topstockresearch.com/INDIAN_STOCKS/COMPUTERS_SOFTWARE/Wipro_Ltd.html'
header = {'User Agent' : 'Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)'}
html_doc=requests.get(x, headers=header)  #With header
html_doc=requests.get(x) #Without Header
soup = BeautifulSoup(html_doc.text, 'lxml')
print(soup)

网址:x=https://www.topstockresearch.com/INDIAN_STOCKS/COMPUTERS_SOFTWARE/Wipro_Ltd.html

感谢阅读!

EDIT2:使用此代码解决:

import requests

session = requests.Session()
response = session.get('https://www.topstockresearch.com/INDIAN_STOCKS/COMPUTERS_SOFTWARE/Wipro_Ltd.html', headers={'User-Agent': 'Mozilla/5.0'})

print(response.text)

PS:我只是学习编码,这不是为了任何与工作相关的目的。只是一个与股市有关的个人项目。

【问题讨论】:

  • 请不要发布代码的图像,将其作为文本发布,以便我们复制粘贴。另外,网址是什么?
  • 如果您不打算分享x 的价值,我们将无法提供帮助:-(
  • 你试过 HTTP GET 到topstockresearch.com/charts/csv/133/73D.csv?var=14 - 它包含有趣的数据。
  • @balderman 感谢您的评论,通过使用请求模块中的 get 函数,我能够从另一个类似的堆栈溢出问题中找到解决方案。

标签: python beautifulsoup screen-scraping


【解决方案1】:

您需要使用User-Agent: 而不是User Agent:。 HTTP 标头不应在其键中使用空格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多