未定义的索引:使用BeatifulSoup / Python的HTTP_ACCEPT_LANGUAGE

时间:2016-08-04 17:07:32

标签: python html-parsing

我正在学习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')

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

任何人都知道我如何定义解析网址?

1 个答案:

答案 0 :(得分:0)

看起来该页面要求您将Accept-Language标头与您的请求一起传递。以下是如何使用requests执行此操作的示例:

import requests

url = "my url"

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