为了完整起见,BeautifulSoup 4版本也使用了服务器提供的编码:from bs4 import BeautifulSoupimport urllib2
resp = urllib2.urlopen("http://www.gpsbasecamp.com/national-parks")soup = BeautifulSoup(resp, from_encoding=resp.info().
getparam('charset'))for link in soup.find_all('a', href=True):
print link['href']
或者Python 3版本:from bs4 import BeautifulSoupimport urllib.request
resp = urllib.request.urlopen("http://www.gpsbasecamp.com/national-parks")soup = BeautifulSoup(resp, from_encoding=resp.info().
get_param('charset'))for link in soup.find_all('a', href=True):
print(link['href'])
和使用requests图书馆,它将在Python 2和3中运行:from bs4 import BeautifulSoupfrom bs4.dammit import EncodingDetectorimport requests
resp = requests.get("http://www.gpsbasecamp.com/national-parks")h