目標(biāo):爬取百度糗事百科段子帘营,url 為http://www.qiushibaike.com/,爬取前20個(gè)網(wǎng)頁中每個(gè)網(wǎng)頁的每個(gè)段子的發(fā)布人琼富、段子內(nèi)容仪吧、點(diǎn)贊數(shù)、評(píng)論數(shù)鞠眉,然后把內(nèi)容保存在一個(gè) BaiduQiushi.txt 文件中薯鼠。
一、 分析網(wǎng)頁結(jié)構(gòu)
通過分析 url 可以發(fā)現(xiàn)規(guī)律械蹋,使用該規(guī)律來實(shí)現(xiàn)換頁功能出皇。
即:” http://www.qiushibaike.com/8hr/page/” + pagenum +”/?s=4966067”
然后查看頁面源代碼,輔助 chrome 審查元素元素功能快速定位所需內(nèi)容位置哗戈。
可以發(fā)現(xiàn)郊艘,每個(gè)段子都是包括在div 標(biāo)簽內(nèi)的。
發(fā)布人:
段子內(nèi)容:
點(diǎn)贊數(shù):
評(píng)論數(shù):
二唯咬、 確定使用技術(shù)路線
這里獲取內(nèi)容的方式有很多種纱注,可以使用 requests + re 。也可是使用 beautifulsoup胆胰。
不過感覺這個(gè)例子比較小狞贱,我就只使用了 requests 和 re 來實(shí)現(xiàn)。
三蜀涨、 步驟
1. 實(shí)現(xiàn)換頁功能瞎嬉,生成 url 列表 urls。
2. 遍歷 urls 這個(gè)列表厚柳,解析每個(gè)頁面的 html 源代碼氧枣。
3. 對(duì)于每個(gè) html,獲得發(fā)布人模塊别垮,放置在 everyblock 列表中便监。
4. 遍歷每個(gè) everyblock 列表,提取每個(gè)段子的發(fā)布人碳想、段子內(nèi)容烧董、點(diǎn)贊數(shù)、評(píng)論數(shù)
四移袍、 代碼
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/3/18 15:10
# @Author : zxp
# @Site :
# @File : zxp_CrowBaiduQiushi.py
# @Software: PyCharm Community Edition
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
print url + ':獲取失敗老充!'
def getEveryBlock(html):
everyblock = re.findall('(<div class="article block untagged mb15".*?<div class="single-clear"></div>)', html, re.S)
return everyblock
def getInfo(block):
info = {}
info['author'] = re.search('<h2>(.*?)</h2>', block, re.S).group(1)
info['content'] = re.search('<span>(.*?)</span>', block, re.S).group(1)
likeandcomment = re.findall('<i class="number">(.*?)</i>', block, re.S)
info['like'] = likeandcomment[0]
if len(likeandcomment) == 1:
info['comment'] = '0'
else:
info['comment'] = likeandcomment[1]
return info
def saveAllInfo(all_info):
f = open('BaiduQiushi.txt', 'a')
for each in all_info:
f.writelines('author:' + each['author'] + '\n')
f.writelines('content:' + each['content'] + '\n')
f.writelines('like:' + each['like'] + '\n')
f.writelines('comment:' + each['comment'] + '\n\n')
f.close()
def main():
urls = []
all_info = []
pagenum = 20
for i in xrange(1, pagenum + 1):
url = 'http://www.qiushibaike.com/8hr/page/' + str(i) + '/?s=4966067'
urls.append(url)
for url in urls:
html = getHTMLText(url)
everyblock = getEveryBlock(html)
for each in everyblock:
info = getInfo(each)
all_info.append(info)
saveAllInfo(all_info)
if __name__ == '__main__':
main()