嗯……之前用Scrapy寫過一個,并且成功爬了下來星岗,奈何效率低下而且配置蛋疼,今天在網(wǎng)易云課堂看到不錯的教程戒洼,用他現(xiàn)成的代碼改了下俏橘,竟也運行成功,而且效率高了不少施逾。在此Mark下敷矫,方便以后參考。
因為論壇限制搜索時間在一年以內(nèi)汉额,為了方便本地查找資源曹仗,因此目標為保存所有的專輯及鏈接到一個HTML中。
思路很簡單蠕搜,首先打開網(wǎng)頁怎茫,篩選需要抓取的數(shù)據(jù)(鏈接、標題)妓灌,保存瀏覽器的Cookies及User-Agent到一個Dict里轨蛤,用requests庫加上之前的User-Agent下載網(wǎng)頁,使用BeautifunSoup解析后虫埂,調試CSS Selector到能夠準確指向所需信息祥山,然后將專輯及對應的鏈接分別放置在一個Dict里,處理輸出即可掉伏。
from bs4 import BeautifulSoup
import requests
import time
#定義需要爬取的頁面及headers
url = 'https://hostname/bbs/thread.php?fid=fid&page=1'
urls = ['https://hostname/bbs/thread.php?fid=fid&page={}'.format(str(i)) for i in range(start,end,step)]
headers = {
'User-Agent':'',
'Cookie':''
}
#爬取專輯信息
def getAlbumInfo(url,data=None):
wb_data = requests.get(url,headers=headers)
time.sleep(4)
soup = BeautifulSoup(wb_data.text,'lxml')
titles = soup.select('tr.t_one > td > h3 > a')
links = soup.select('tr.t_one > td > h3 > a')
data = []
if data == []:
for titles,links in zip(titles,links):
datas = {
'title' :titles.get_text(),
'link' :links.get('href'),
}
data.append(datas)
print(data)
return data
#遍歷爬取結果及輸出為HTML鏈接
def dataProcessAndWriteToFile(result):
for links in result:
url = '<a '+'href=https://hostname/bbs/'+str(links['link'])+'>'+str(links['title'])+'</a>'+'</br>'
print(url)
f = open('output.html','a',encoding='utf-8')
f.write(url)
f.close()
#執(zhí)行
for url in urls:
current = getAlbumInfo(url)
dataProcessAndWriteToFile(current)