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

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


我比較懶,這里就不每個(gè)函數(shù)細(xì)介紹了,一會(huì)貼完整代碼,代碼里寫(xiě)了一些注釋?zhuān)蠹易约嚎窗伞?
三、代碼自我評(píng)價(jià)
1:這些代碼優(yōu)化空間應(yīng)該還挺大的,比如寫(xiě)入excel的數(shù)據(jù),我這里采用的是將所有的數(shù)據(jù)存到一個(gè)列表里面,然后再取出來(lái)寫(xiě)入excel文件。
2:這里我也沒(méi)有寫(xiě)多線程。里面for寫(xiě)的有點(diǎn)多,寫(xiě)多線程怕搞懵了。(反正也是寫(xiě)著玩的,就沒(méi)在意爬取效率了)(PS:其實(shí)我多線程還不怎么會(huì)用,哈哈)
3:我把代碼丟到服務(wù)器爬了一個(gè)類(lèi)型的所有個(gè)人微信號(hào)信息。爬完有(1162條信息),二維碼也都是以類(lèi)似標(biāo)題名稱(chēng)創(chuàng)建的文件夾下面。
大家運(yùn)行改下相應(yīng)的存儲(chǔ)路徑吧。
此代碼請(qǐng)勿商用,如侵犯?jìng)€(gè)人信息還請(qǐ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):
'''解析頁(yè)面源碼'''
try:
#添加瀏覽器頭,訪問(wèn)超時(shí)
html = requests.get(url,headers=headers,timeout=30)
html.raise_for_status()
html.encoding = html.apparent_encoding
return html.text
except:
print('獲取頁(yè)面源碼失敗')
def getchaturls(html):
'''獲取每頁(yè)信息詳情鏈接'''
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('獲取頁(yè)面詳細(xì)詳細(xì)鏈接失敗')
def getinfo(url,infos):
'''獲取鏈接詳情頁(yè)面所需信息'''
try:
picurls = []
html = gethtml(url)
soup = BeautifulSoup(html,'lxml')
pic = soup.find('div',class_='iframe')
x = pic.find_all('span',class_='shiftcode')
#判斷是否詳情頁(yè)面是否有群主及群二維碼
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'])
#找到詳情頁(yè)面需要數(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(' ',''))
#獲取微信號(hào)
waccount = clearfix.find_all('span',class_='des_info_text2')
infos.append('微信號(hào):'+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('詳情頁(yè)面解析失敗')
def saveinfo(infoms):
'''保存excel文件'''
wb = xlwt.Workbook()
ws = wb.add_sheet('wchat')
ws.write(0, 0, '行業(yè)')
ws.write(0, 1, '時(shí)間')
ws.write(0, 2, '地區(qū)')
ws.write(0, 3, '標(biāo)簽')
ws.write(0, 4, '微信號(hào)')
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):
'''保存群或群主/個(gè)人微信二維碼'''
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): #頁(yè)面默認(rèn)第一頁(yè)為0,請(qǐng)至頁(yè)面查看最后一頁(yè)的數(shù)字,將最后一頁(yè)數(shù)字加1輸入括號(hào)第二位置
#如需其他類(lèi)型,請(qǐng)至瀏覽器查看對(duì)應(yīng)類(lèi)型鏈接的t值,如微信群鏈接開(kāi)頭為:http://www.weixinqun.com/group,個(gè)人鏈接開(kāi)頭為:http://www.weixinqun.com/personal
first_url = 'http://www.weixinqun.com/personal?t=52&p={}'.format(page)
print('正在處理第{}頁(yè),鏈接為:{}'.format(page,first_url))
html = gethtml(first_url)
urls = getchaturls(html)
for url in urls:
print('=====分隔符=====')
print('正在處理第{}頁(yè),內(nèi)容詳情鏈接為:{}'.format(page,url))
getinfo(url,infos)
infoa = infossplit(infos)
print(infos)
saveinfo(infoa)
print('=====全部處理完成=====')
if __name__=='__main__':
main()