什么是爬蟲
按照一定規(guī)則自動的獲取互聯(lián)網(wǎng)上的信息(如何快速有效的利用互聯(lián)網(wǎng)上的大量信息)
爬蟲的應(yīng)用
- 搜索引擎(Google、百度膘格、Bing等搜索引擎芳绩,輔助人們檢索信息)
- 股票軟件(爬取股票數(shù)據(jù)催什,幫助人們分析決策凤覆,進(jìn)行金融交易)
- Web掃描(需要對網(wǎng)站所有的網(wǎng)頁進(jìn)行漏洞掃描)
- 獲取某網(wǎng)站最新文章收藏
- 爬取天氣預(yù)報
- 爬取漂亮mm照片
…
基礎(chǔ)知識
1.HTTP 協(xié)議
客戶端發(fā)起請求,服務(wù)器接收到請求后返回格式化的數(shù)據(jù)发乔,客戶端接收數(shù)據(jù)熟妓,并進(jìn)行解析和處理
2.HTML(超文本標(biāo)記語言)
html.png
3.Python
- 基礎(chǔ)語法&常用系統(tǒng)模塊
- 第三方模塊requests,pyquery使用
安裝:
pip install requests
pip install pyquery
requests模塊使用:
#requests(發(fā)起HTTP請求,并獲取結(jié)果)
response = requests.get('http://localhost:9999/index.html')
response = requests.post()
print response.content
pyquery模塊使用
page = PyQuery(html)
選擇器
tag: page('title')
id: page('#job_1')
class: page('.job')
復(fù)合選擇器
page('div#job_1')
page('div.job')
子選擇器
page('div#job_1 li')
page('div#job_1 > li')
page('div#job_1').find('li')
page('div#job_1').children('li')
獲取標(biāo)簽內(nèi)的html page('div#job_1').html()
獲取標(biāo)簽內(nèi)的文本 page('div#job_1').text()
獲取標(biāo)簽屬性 page('div#job_1').attr['id']
csv模塊使用
writer = csv.writer()
writer.writerow()
writer.writerows()
程序運行
1.程序啟動
start.png
2.運行結(jié)果
result.png
手動搜索TOP N電影信息
1.獲取電影列表
list.png
2.獲取電影詳情超鏈接
link.png
3.獲取電影詳情
info.png
代碼走讀
1.程序啟動
main.png
2.查找電影列表
list.png
3.查找電影詳情
info.png
4.寫入csv文件
csv.png
源碼
#encoding: utf-8
import requests
from pyquery import PyQuery as pq
import csv
attrs = [u'超鏈接', u'名稱', u'評分', u'導(dǎo)演', u'編劇', u'主演', u'類型', u'制片國家/地區(qū)', u'語言', u'上映日期', u'片長', u'又名', u'IMDb鏈接']
'''
獲取電影詳情
'''
def attch_info(info, text, key, value):
text = text.strip(' ')
if text:
if text in attrs:
if key and value:
info[key] = ' '.join(value)
key = text
value = []
else:
value.append(text)
return info, key, value
'''
解析電影信息
'''
def parse_movie_info(text, info):
key = None
value = []
for e in text.split(':'):
e = e.strip()
pos = e.rfind(' ')
if -1 == pos:
info, key, value = attch_info(info, e, key, value)
else:
info, key, value = attch_info(info, e[:pos], key, value)
info, key, value = attch_info(info, e[pos:], key, value)
if key not in info:
info[key] = ' '.join(value)
'''
解析電影頁面
'''
def crawl_info(url):
info = {}
print url
response = requests.get(url)
page = pq(response.content)
content = page('div#content').eq(0)
info[u'超鏈接'] = url
info[u'名稱'] = content('h1 span').eq(0).text()
info[u'評分'] = content('div.rating_wrap strong.rating_num').text()
info_text = content('div#info').text()
parse_movie_info(info_text, info)
return info
'''
獲取電影列表
'''
def crawl(query_text, count):
start = 0
rt_list = []
isStop = False
url = 'https://movie.douban.com/subject_search?start={start}&search_text={query_text}&cat=1002'
while True:
response = requests.get(url.format(query_text=query_text.encode('utf-8', 'ignore'), start=start))
page = pq(response.content)
links = page('div#content table a').not_('.nbg')
if len(links) == 0:
isStop = True
for link in links:
href = pq(link).attr['href']
rt_list.append(crawl_info(href))
start += 1
if len(rt_list) >= count:
isStop = True
break
if isStop:
break
return rt_list
'''
寫入文件
'''
def write_to_file(lines, path):
with open(path, 'wb') as fhandler:
writer = csv.writer(fhandler)
writer.writerow(map(lambda x: x.encode('gbk', 'ignore'), attrs))
for line in lines:
row = []
for key in attrs:
row.append(line.get(key, '').encode('gbk', 'ignore'))
writer.writerow(row)
if __name__ == '__main__':
query_text = raw_input(u"請輸入關(guān)鍵字:".encode('utf-8', 'ignore'))
count = raw_input(u"請輸入爬取得數(shù)據(jù)量:".encode('utf-8', 'ignore'))
query_text = query_text.strip().decode('utf-8') if query_text.strip() else u'長城'
count = int(count) if count.isdigit() else 10
print u'關(guān)鍵字:{query_text}, 數(shù)量:{count}'.format(query_text=query_text, count=count)
rt_list = crawl(query_text, count)
write_to_file(rt_list, 'result.csv')