環(huán)境:
- win10 64位
- python3.5.2
相關(guān)庫
- urllib
- pymysql
- json
爬文章入口
baseurl : http://www.toutiao.com/search_content

- (ps:圖片來自網(wǎng)絡(luò))
接觸python,發(fā)現(xiàn)python真是一門讓人上癮的語言,簡單好用效率高.
不多說,直接看要做什么吧.每天看頭條也是一種樂趣,當(dāng)想看同一類型的頭條新聞時(shí),可以直接搜索關(guān)鍵字,突然間對這個(gè)搜索接口感興趣了,為什么不把這些搜到的文章存下來然后想什么時(shí)候看就什么時(shí)候看呢?
打開頭條搜索F12看看它的網(wǎng)絡(luò)請求.

參數(shù)
offset=40&format=json&keyword=%E7%A8%8B%E5%BA%8F%E5%91%98&autoload=true&count=20&cur_tab=1
用代碼構(gòu)造參數(shù),模擬請求
#構(gòu)造請求參數(shù),模擬請求
def get_index_page(offset, keyword):
query_data = {
'offset': offset,
'format': 'json',
'keyword': keyword,
'autoload': 'true',
'count': 20, # 每次返回 20 篇文章
'cur_tab': 1
}
params = urlencode(query_data)
# 頭條搜索api基礎(chǔ)入口
base_url = 'http://www.toutiao.com/search_content/'
url = base_url + '?' + params
print(url)
try:
response = requests.get(url)
if response.status_code == 200:
#print(response.text)
return response.text
return None
except RequestException:
print("頁面索引出錯(cuò),url")
return None
用print看看返回的結(jié)果是啥,分析請求結(jié)果(ps:每次寫爬蟲的時(shí)候總是覺得分析這個(gè)請求結(jié)果是最費(fèi)時(shí)間的,但有時(shí)最關(guān)鍵的,每次還要對著頁面去查這些字段的意義)

找到一些想要要的信息,關(guān)鍵是title,article_url
# 解析數(shù)據(jù),獲取想要的數(shù)據(jù)
def parse_index_page(html):
params = []
data = json.loads(html)
datas = data['data']
for item in datas:
if 'title' in item:#文章標(biāo)題
title = item['title']
if 'source' in item:#資源歸屬
source = item['source']
if 'article_url' in item:#資源鏈接
url = item['article_url']
if 'share_url' in item:#分享鏈接,可作資源鏈接用
share_url = item['share_url']
if 'keywords' in item:#所屬關(guān)鍵詞
keyword = item['keywords']
if 'comment_count' in item:#評論數(shù)
countgood = item['comment_count']
if 'has_video' in item:#是否是視頻鏈接
has_video = item['has_video']
params.append([title, source, url, share_url, keyword, countgood, has_video])
return params
已經(jīng)拿到一些數(shù)據(jù)了,要對數(shù)據(jù)進(jìn)行儲存
使用的pymysql庫進(jìn)行MySQL數(shù)據(jù)庫操作
# 需要指定編碼集,不然會出異常!!!(很重要)
db = pymysql.connect("localhost", "用戶名", "密碼", "數(shù)據(jù)庫名稱", use_unicode=True, charset='utf8')
cursor = db.cursor()
#儲存至數(shù)據(jù)庫
def save_data(params):
try:
sql = 'INSERT INTO toutiao_python VALUES (%s,%s,%s,%s,%s,%s,%s)'
# 批量插入數(shù)據(jù)庫
cursor.executemany(sql, params)
db.commit()
except Exception as e:
print(e)
db.rollback()
之前直接的想法是查到一條數(shù)據(jù)儲存一條數(shù)據(jù),發(fā)現(xiàn)效率太低了,仔細(xì)想了下,這么好用的語言不可能不能批量儲存數(shù)據(jù),仔細(xì)找了下api 發(fā)現(xiàn)cursor.executemany(sql, params)這個(gè)方法能批量儲存數(shù)據(jù),效率提升很多.
最后開個(gè)多線程來加快爬蟲效率
# 指定搜索的參數(shù)offset范圍為[CRAWLER_GO*20,(CRAWLER_END+1)*20]
CRAWLER_GO = 1
CRAWLER_END = 50
# 搜索關(guān)鍵字,可以改變
# 開啟多線程
if __name__ == '__main__':
pool = Pool()
group = [x * 20 for x in range(CRAWLER_GO, CRAWLER_END + 1)]
pool.map(main, group)
pool.close()
pool.join()
-
運(yùn)行結(jié)果
