Skip to main content
 首页 » 编程设计

python之未定义索引 : HTTP_ACCEPT_LANGUAGE using BeatifulSoup/Python

2025年04月02日10del

我正在学习 Python,我正在尝试使用 BeautifulSoup 解析用 PHP 制作的网页。我的问题是我的脚本显示此错误:

<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;"> 
<h4>A PHP Error was encountered</h4> 
<p>Severity: Notice</p> 
<p>Message:  Undefined index: HTTP_ACCEPT_LANGUAGE</p> 
<p>Filename: hooks/detecta_idioma.php</p> 
<p>Line Number: 110</p> 
</div> 

当我尝试这样做时

html = urllib.urlopen(url).read() 
web = BeautifulSoup(html,'html.parser') 
print web 
etiquetas = web('a') 

我认为这个错误是通过命令行而不是使用网络浏览器执行我的脚本,但是,从 Apache 执行这个脚本,我有同样的错误。

有人知道我如何定义它来解析 url 吗?

请您参考如下方法:

看起来该页面要求您将 Accept-Language header 与您的请求一起传递。这是一个如何用 requests 做到这一点的例子:

import requests 
 
url = "my url" 
 
response = requests.get(url, headers={"Accept-Language": "en-US,en"}) 
html = response.content 
web = BeautifulSoup(html, 'html.parser')