【发布时间】:2014-07-06 06:32:50
【问题描述】:
我有一个简单的网站爬虫,它工作正常,但有时它会因为 ISO 映像、.exe 文件和其他大文件等大内容而卡住。使用文件扩展名猜测内容类型可能不是最好的主意。
是否可以在不获取整个内容/页面的情况下获取内容类型和内容长度/大小?
这是我的代码:
requests.adapters.DEFAULT_RETRIES = 2
url = url.decode('utf8', 'ignore')
urlData = urlparse.urlparse(url)
urlDomain = urlData.netloc
session = requests.Session()
customHeaders = {}
if maxRedirects == None:
session.max_redirects = self.maxRedirects
else:
session.max_redirects = maxRedirects
self.currentUserAgent = self.userAgents[random.randrange(len(self.userAgents))]
customHeaders['User-agent'] = self.currentUserAgent
try:
response = session.get(url, timeout=self.pageOpenTimeout, headers=customHeaders)
currentUrl = response.url
currentUrlData = urlparse.urlparse(currentUrl)
currentUrlDomain = currentUrlData.netloc
domainWWW = 'www.' + str(urlDomain)
headers = response.headers
contentType = str(headers['content-type'])
except:
logging.basicConfig(level=logging.DEBUG, filename=self.exceptionsFile)
logging.exception("Get page exception:")
response = None
【问题讨论】:
-
不是存储在变量
contentType中吗? -
是的,它存储在 contentType 中,但内容已经获取。
-
啊我明白你的意思。看看我的回答。
标签: python http-headers content-type python-requests