我正在尝试从 NASA 网站上抓取一些 div
并将所有内容放入列表中。 此代码之前可以运行,但突然决定不再运行。除了添加一些打印语句之外,我没有故意更改任何内容,所有这些语句都不返回任何内容或 []
,没有任何类型的错误。
import re
import urllib2
from BeautifulSoup import BeautifulSoup as soup
import ssl
url = "https://climate.nasa.gov"
context = ssl._create_unverified_context()
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
web_soup = soup(urllib2.urlopen(url, context=context))
l = []
# get main-content div
main_div = web_soup.findAll(name="div", attrs={'class': 'change_number'})
print main_div
for element in main_div:
print element
l.append(float(str(element)[27:-7]))
print l
任何有关查明此突然错误的帮助将不胜感激!
UPDATE1:刚刚在解释器中尝试过,以同样的方式失败。 main_div
似乎正在返回 []
。
UPDATE2:刚刚检查了网站以确保 div change_number
存在。确实如此。
UPDATE3:现在我真的很困惑。我有这段代码,我很确定它与上面的代码基本相同:
import re
import urllib2
from BeautifulSoup import BeautifulSoup as soup
import ssl
url = "https://climate.nasa.gov"
context = ssl._create_unverified_context()
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
web_soup = soup(urllib2.urlopen(url, context=context))
l = []
# get main-content div
main_div = web_soup.findAll(name="div", attrs={'class': 'change_number'})
for element in main_div:
print element
l.append(float(str(element)[27:-7]))
print l
但它在 websoup 定义行上抛出 UnicodeEncodeError
:
Traceback (most recent call last):
File "climate_nasa_change.py", line 10, in <module>
web_soup = soup(urllib2.urlopen(url, context=context))
File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1522, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1147, in __init__
self._feed(isHTML=isHTML)
File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1189, in _feed
SGMLParser.feed(self, markup)
File "C:\Python27\lib\sgmllib.py", line 104, in feed
self.goahead(0)
File "C:\Python27\lib\sgmllib.py", line 143, in goahead
k = self.parse_endtag(i)
File "C:\Python27\lib\sgmllib.py", line 320, in parse_endtag
self.finish_endtag(tag)
File "C:\Python27\lib\sgmllib.py", line 358, in finish_endtag
method = getattr(self, 'end_' + tag)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 11-12: ordinal not in range(128)
更新4:aaaaaaaaaaaaaa现在它神奇地工作了。我真的不知道现在到底发生了什么。
更新5:现在它坏了。我发誓我不会改变。认真考虑驱除我的电脑。请帮忙。
更新6:刚刚尝试 ping Climate.nasa.gov。尽管页面始终在我的浏览器中加载,但它并不总是能够通过。这会导致 BeautifulSoup 失败吗?
最佳答案
问题在于该网站有时会返回 gzip 编码的响应,有时会返回纯文本。
如果您使用 requests
,您可以轻松解决此问题,因为它会自动解码内容:
web_soup = soup(requests.get(url, verify=False).text)
请注意,requests
不是标准库,您必须安装它。
如果您坚持使用 urllib2
,则可以使用 zlib
解码响应(如果已编码):
decode = lambda response : zlib.decompress(response, 16 + zlib.MAX_WBITS)
response = urllib2.urlopen(url, context=context)
headers = response.info()
html = decode(response.read()) if headers.get('content-encoding') == 'gzip' else response
web_soup = soup(html)
关于python - BeautifulSoup </div> 抓取突然停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44895028/