美汤4不Working/Consistent

Beautiful Soup 4 Not Working/Consistent

尽管我编写的脚本有效,但并非所有网站都有自己的标题 returned(这就是我要做的,获取网站的标题并将其打印回来)。 google 之类的网站可以正常工作,但其他网站(例如本网站 Whosebug)会生成错误。

这是我的代码:

    import urllib2
    from bs4 import BeautifulSoup

    soup = BeautifulSoup(urllib2.urlopen("http://lxml.de"))
    print soup.title.string

如果你能为我做这些事情就好了:)

  1. 如果可以对代码(和处理变量)进行任何改进
  2. 如何解决它不存在的问题return(并处理一般错误)
  3. 代码实际上 return 是一个 USERWARNING(当它实际工作时)说我应该在脚本后添加一个特殊的 "html.parser" 但是我把它放进去后它没有工作。

顺便说一句,给出的错误(正如它吐出的那样):

Traceback (most recent call last):
  File "C:\Users\NAME\Desktop\NETWORK\personal work\PROGRAMMING\Python\bibli
ography PYTHON\TEMP.py", line 5, in <module>
    soup = BeautifulSoup(urllib2.urlopen("
96222/beautiful-soup-4-not-working-consistent"))
  File "C:\Program Files (x86)\PYTHON 27\lib\urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Program Files (x86)\PYTHON 27\lib\urllib2.py", line 437, in open
    response = meth(req, response)
  File "C:\Program Files (x86)\PYTHON 27\lib\urllib2.py", line 550, in http_resp
onse
    'http', request, response, code, msg, hdrs)
  File "C:\Program Files (x86)\PYTHON 27\lib\urllib2.py", line 475, in error
    return self._call_chain(*args)
  File "C:\Program Files (x86)\PYTHON 27\lib\urllib2.py", line 409, in _call_cha
in
    result = func(*args)
  File "C:\Program Files (x86)\PYTHON 27\lib\urllib2.py", line 558, in http_erro
r_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
Press any key to continue . . .

尝试this url library

pip install requests   

下面的代码适合我

import requests
from bs4 import BeautifulSoup
htmlresponse = requests.get("http://lxml.de/")
print htmlresponse.content

我可以通过指定用户代理 header 来让它工作。我感觉跟 https 和 http 有关系,但恐怕我不完全确定原因是什么。

import urllib2
from bs4 import BeautifulSoup

site= "https://whosebug.com"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'}

req = urllib2.Request(site, headers=hdr)

try:
    soup = BeautifulSoup(urllib2.urlopen(req), "html.parser")
except urllib2.HTTPError, e:
    print e.fp.read()

print soup.title.string

这受到 by this answer 另一个问题的影响。