GET请求/百度贴吧 有bug

 #  -*- coding:utf-8 -*-
import urllib, urllib2
import re
import sys class Cuzz():
"""这是一个类"""
def __init__(self, url, header, start_page, end_page):
self.url = url
self.header = header
self.start_page = start_page
self.end_page = end_page def deal_url(self):
"""处理url"""
for i in range(self.start_page, self.end_page+1):
num = 50*(i-1)
url = self.url+str(num)
request = urllib2.Request(url, headers=self.header)
response = urllib2.urlopen(request)
htmltext = response.read()
self.load_images(htmltext) def load_images(self, htmltext):
"""下载图片"""
# 找出这一页的所有帖子类似这样的/p/1111111111
pattern = re.findall(r"/p/\d+", htmltext)
for temp in pattern:
url = "http://tieba.baidu.com" + temp
request = urllib2.Request(url, headers=self.header)
response = urllib2.urlopen(request)
htmltext1 = response.read()
self.save_images(htmltext1) def save_images(self, htmltext1):
"""保存到本地"""
image_links = re.findall(r"https://imgsa\.baidu.+?\.jpg",htmltext1)
for url in image_links:
request = urllib2.Request(url, headers=self.header)
response = urllib2.urlopen(request)
htmltext1 = response.read()
print htmltext1
with open("./images/"+str(url[-10:-1]), "w") as f:
f.write(htmltext1) def main():
"""控制"""
header = {"User-Agent":"Mozilla/5.0(WindowsNT6.1;rv:2.0.1)Gecko/20100101Firefox/4.0.1"}
title = raw_input("请输入您要下载的贴吧:")
keyword = {"kw":title} # 是一个字典的格式,转换后"kw=%34dgfdg%fg keyword = urllib.urlencode(keyword) # 有中文需要转成url的格式 url = "https://tieba.baidu.com/f?" + keyword + "&ie=utf-8&pn=" start_page = int(raw_input("请输入起始页面:"))
end_page = int(raw_input("请输入截止页面:")) cuzz = Cuzz(url, header, start_page, end_page)
cuzz.deal_url()
上一篇:浅谈Tarjan算法


下一篇:Building,Packaging,Deploying,and Administering Applications and Types