更多教程請移步至:洛涼博客
求助請移步至:Python自學(xué)技術(shù)交流
一、介紹
最近一直在寫爬蟲,前幾天和老哥聊天。(老哥任職于某醫(yī)療公司)老哥也在研究爬蟲。我就問他爬什么網(wǎng)站。然后老哥直接給我發(fā)了鏈接過來。我看了下:是個小網(wǎng)站。一看就挺好爬的。然后自己就寫起代碼來了。
網(wǎng)站為:http://www.weixinqun.com/。這個網(wǎng)站也真是絕了,各種行業(yè)個人,群信息都有。
有需要的也可以去試試。
這代碼從周五晚上斷斷續(xù)續(xù),一直寫到今天上午才算真正調(diào)試完了。
晚上睡覺都在想出問題的地方改這么處理。
二、爬取思路
思路還是老套路。
用的模塊我這里直接貼出來。1.requests,2.bs4,3.xlwt,4.md5,5.os
也就是一些定向爬蟲常用的一些模塊。
由于數(shù)據(jù)比較多。這里采用的是excel保存相關(guān)信息,二維碼單獨(dú)存在標(biāo)題目錄下。
之前沒看過xlwt模塊,昨天晚上一直在研究這模塊,官方示例代碼很好理解。
QQ群里有朋友介紹用CVS保存。據(jù)他說比excel更簡單。(后續(xù)我也去看看這模塊)
代碼里面除了主函數(shù)有6個函數(shù)。這里介紹下吧。
第一個函數(shù):獲取頁面源碼
第二個函數(shù):通過一個函數(shù)獲取到的源碼,再獲取每頁的列表里數(shù)據(jù)詳細(xì)鏈接
第三個函數(shù):獲取每個詳細(xì)鏈接里面的數(shù)據(jù)

第四個函數(shù):將獲取到的寫入excel文件
第五個函數(shù):保存二維碼圖片至本地
第六個函數(shù):將獲取到的信息切片,方便存入excel。


我比較懶,這里就不每個函數(shù)細(xì)介紹了,一會貼完整代碼,代碼里寫了一些注釋,大家自己看吧。
三、代碼自我評價
1:這些代碼優(yōu)化空間應(yīng)該還挺大的,比如寫入excel的數(shù)據(jù),我這里采用的是將所有的數(shù)據(jù)存到一個列表里面,然后再取出來寫入excel文件。
2:這里我也沒有寫多線程。里面for寫的有點(diǎn)多,寫多線程怕搞懵了。(反正也是寫著玩的,就沒在意爬取效率了)(PS:其實我多線程還不怎么會用,哈哈)
3:我把代碼丟到服務(wù)器爬了一個類型的所有個人微信號信息。爬完有(1162條信息),二維碼也都是以類似標(biāo)題名稱創(chuàng)建的文件夾下面。
大家運(yùn)行改下相應(yīng)的存儲路徑吧。
此代碼請勿商用,如侵犯個人信息還請告知,本人立馬刪除!
import requests
from bs4 import BeautifulSoup
import bs4
import xlwt
from hashlib import md5
import os
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
def gethtml(url):
'''解析頁面源碼'''
try:
#添加瀏覽器頭,訪問超時
html = requests.get(url,headers=headers,timeout=30)
html.raise_for_status()
html.encoding = html.apparent_encoding
return html.text
except:
print('獲取頁面源碼失敗')
def getchaturls(html):
'''獲取每頁信息詳情鏈接'''
try:
soup = BeautifulSoup(html,'html.parser')
chat_url = []
for chat in soup.find_all('div',class_='border5'):
chat = chat.a.attrs['href']
chat_url.append('http://www.weixinqun.com'+chat)
return chat_url
except:
print('獲取頁面詳細(xì)詳細(xì)鏈接失敗')
def getinfo(url,infos):
'''獲取鏈接詳情頁面所需信息'''
try:
picurls = []
html = gethtml(url)
soup = BeautifulSoup(html,'lxml')
pic = soup.find('div',class_='iframe')
x = pic.find_all('span',class_='shiftcode')
#判斷是否詳情頁面是否有群主及群二維碼
if len(x) == 2:
picurls.append(x[0].img.attrs['src'])
picurls.append(x[1].img.attrs['src'])
else:
picurls.append(pic.img.attrs['src'])
#找到詳情頁面需要數(shù)據(jù)所在的標(biāo)簽
clearfix = soup.find('div',class_='des_info')
#在需要的標(biāo)簽內(nèi)獲取標(biāo)題
title = clearfix.find('span',class_='des_info_text').get_text().replace('\n','').replace(' ','').replace(':','')
#獲取詳細(xì)信息
for info in clearfix.find('ul').children:
if isinstance(info, bs4.element.Tag):
other = info('li')
for a in other:
infos.append(a.get_text().replace('\n','').replace(' ',''))
#獲取微信號
waccount = clearfix.find_all('span',class_='des_info_text2')
infos.append('微信號:'+waccount[1].get_text().replace('\n','').replace(' ',''))
#獲取熱度
hot = clearfix.find_all('span',class_='Pink')
infos.append('熱度:'+hot[0].get_text().replace('\n','').replace(' ',''))
print('正常處理的詳情標(biāo)題:{}'.format(title))
#調(diào)用保存二維碼方法
savepic(picurls,title)
except:
print('詳情頁面解析失敗')
def saveinfo(infoms):
'''保存excel文件'''
wb = xlwt.Workbook()
ws = wb.add_sheet('wchat')
ws.write(0, 0, '行業(yè)')
ws.write(0, 1, '時間')
ws.write(0, 2, '地區(qū)')
ws.write(0, 3, '標(biāo)簽')
ws.write(0, 4, '微信號')
ws.write(0, 5, '熱度')
pp = 1
for b in range(0, len(infoms), 6):
ws.write(pp, 0, infoms[b])
ws.write(pp, 1, infoms[b + 1])
ws.write(pp, 2, infoms[b + 2])
ws.write(pp, 3, infoms[b + 3])
ws.write(pp, 4, infoms[b + 4])
ws.write(pp, 5, infoms[b + 5])
pp += 1
wb.save('D://微信群//wchat.xls')
def savepic(picurls,title):
'''保存群或群主/個人微信二維碼'''
path = 'D://微信群//'
if not os.path.exists(path):
os.mkdir(path)
path1 = path+title+'//'
if not os.path.exists(path1):
os.mkdir(path1)
for url in picurls:
photo = requests.get(url,headers=headers).content
filename = md5(photo).hexdigest()
with open(path1+filename+'.jpg','wb') as f:
f.write(photo)
f.close()
def infossplit(infos):
'''字符串切片操作'''
infoms = []
for info in infos:
info = info.split(':')[1]
infoms.append(info)
return infoms
def main():
'''程序入口'''
#創(chuàng)建空列表存放詳情
infos = []
for page in range(0,13): #頁面默認(rèn)第一頁為0,請至頁面查看最后一頁的數(shù)字,將最后一頁數(shù)字加1輸入括號第二位置
#如需其他類型,請至瀏覽器查看對應(yīng)類型鏈接的t值,如微信群鏈接開頭為:http://www.weixinqun.com/group,個人鏈接開頭為:http://www.weixinqun.com/personal
first_url = 'http://www.weixinqun.com/personal?t=52&p={}'.format(page)
print('正在處理第{}頁,鏈接為:{}'.format(page,first_url))
html = gethtml(first_url)
urls = getchaturls(html)
for url in urls:
print('=====分隔符=====')
print('正在處理第{}頁,內(nèi)容詳情鏈接為:{}'.format(page,url))
getinfo(url,infos)
infoa = infossplit(infos)
print(infos)
saveinfo(infoa)
print('=====全部處理完成=====')
if __name__=='__main__':
main()