python爬虫爬取的页面使用了gzip压缩的问题

当在headers中加了一个Accept-encoding:......时,返回的页面可能是经过了压缩的;即使没有加这个属性,返回的网页也可能是经过了压缩的(服务器自动压缩的)

我在爬取笔趣阁的某个网页时就遇到了被gzip压缩了的网页

 1 #-*-coding:utf-8 -*-
 2 
 3 import time
 4 import re
 5 import gzip
 6 import urllib.request
 7 from bs4 import BeautifulSoup
 8 from io import StringIO
 9 # import StringIO
10 
11 url = "http://www.shuquge.com/txt/5760/index.html"
12 header = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36", "Accept-Encoding":""}
13 page = urllib.request.Request(url, headers = header)
14 gs = urllib.request.urlopen(page)
15 # gs = StringIO(gs)
16 # print(gs)
17 
18 page_info = gzip.GzipFile(fileobj=gs)
19 
20 page_info = page_info.read()
21 page_info = page_info.decode('utf-8')
22 print(page_info)

里面用了gzip模块,因为一开始看别人的博客以为要用到StringIO结果并不需要。

里面用到了gzip.GzipFile()方法,以及gzip对象的read()方法。

posted @ 2022-01-20 10:08  the_sky314  阅读(716)  评论(0编辑  收藏  举报