马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
学习了python将近一年了,最近有空得以学学爬虫,还是挺好玩的,用鱼C论坛也挺久了经常看一些大佬操作,作为菜鸟的我第一次发这个帖子,希望大家多多支持啦import requests,re,numpy,pandas,time,random
class Baidupic:
def __init__(self):
a = input('请输入要爬取的贴吧名')
n = 0
self.o = 1
self.h = 1
for i in range(2):
tw = i+1
print('正在爬取'+str(tw)+'页')
url = 'https://tieba.baidu.com/f?ie=utf-8&kw='+a+'&ie=utf-8&pn='+str(n)
self.headers = [{'User-Agent' :'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.16 Safari/537.36'},
{'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360EE'},
{'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1'},
{'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0'},
{'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'},
{'User-Agent':'Opera/9.80 (Windows NT 6.1; U; zh-cn) Presto/2.9.168 Version/11.50'},
{'User-Agent':'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3'}]
html = requests.get(url = url ,headers = random.choice(self.headers))
self.html = html.text
self.data()
n += 50
def data(self):
# t = re.findall(r'original="(.*?)"',self.html)
t1 = re.findall(r"data-tid='(.*?)'",self.html)
# t2 = re.findall(r'title: "(.*?)"',self.html)
# print(t1)
if (len(t1) > 0):
try:
for i in t1:
url = 'https://tieba.baidu.com/p/'+str(i)
html = requests.get(url = url ,headers = random.choice(self.headers))
data = html.text
s = re.findall(r'src="(.*?.jpg)" size="',data)
if (len(s)>0):
for n in s:
#print(n)
with open('E:\\Administrator\\pic\\' + str(self.h) + '.jpg','wb') as f:
try:
tt = requests.get(url = n,headers = random.choice(self.headers))
f.write(tt.content)
print(self.h)
self.h += 1
except Exception:
break
else:
print('这个帖子里没有图片')
except Exception:
return
time.sleep(3)
if __name__ == '__main__':
app = Baidupic()
|