不用python爬今日头条_手把手教你从今日头条爬取你想要的任何图片
都說人生苦短,我用python。為了找點(diǎn)樂趣,不如寫個(gè)爬蟲?
那爬什么呢?
宇宙條是爬蟲界行家,它的很多信息都是從其它網(wǎng)站爬來的,那就拿它練練手吧。
網(wǎng)上類似的文章其實(shí)不少,但是大多是很久之前的,在這期間頭條已經(jīng)做了改版,因此還必須自己動(dòng)手。
具體原理不多說了,直接簡(jiǎn)單介紹下步驟:
1.首先,打開頭條首頁,搜索關(guān)鍵詞「美景」,可以得到搜索結(jié)果頁面鏈接為https://www.toutiao.com/search/?keyword=美景?,搜索結(jié)果如下:
image
2.同時(shí)注意到這是一個(gè)Ajax請(qǐng)求,因此我們需要拿到其真實(shí)的請(qǐng)求url,就是圖中紅框標(biāo)出來的部分。
3.第一次發(fā)起搜索請(qǐng)求時(shí),頭條有一個(gè)滑塊驗(yàn)證,這里我們就不模擬這個(gè)過程了,手動(dòng)驗(yàn)證,拿到cookie就好,同時(shí)將自己的瀏覽器信息,請(qǐng)求參數(shù)都復(fù)制出來:
image
連續(xù)向后翻頁,發(fā)現(xiàn)變化的參數(shù)只有offset一個(gè),也就是偏移量。
4.觀察請(qǐng)求結(jié)果,最關(guān)鍵的是article_url這個(gè)字段,根據(jù)這個(gè)鏈接重定向,就可以跳轉(zhuǎn)到列表中每篇文章的詳情頁。
image
5.進(jìn)入詳情頁,查看網(wǎng)頁源碼,可以發(fā)現(xiàn)圖片鏈接都是以下圖標(biāo)出來的形式記錄的,這就好辦了,簡(jiǎn)單正則匹配一下就好
image
6.拿到圖片鏈接,保存到本地,大功告成。
image
應(yīng)該說頭條相對(duì)來說做得比較簡(jiǎn)單一些,畢竟是新聞?lì)惥W(wǎng)站,總共差不多100行代碼就搞定了,不像淘寶,要爬它的數(shù)據(jù)就要困難很多。
當(dāng)然了,除了爬美景,其它照片你想爬啥就怕啥,修改下搜索關(guān)鍵字就好了。第一次寫爬蟲,還有很多可以優(yōu)化的地方。簡(jiǎn)單貼下代碼,需要的自取,鬼曉得頭條啥時(shí)候又改版了,同時(shí)歡迎大家review😆。
最后,祝各位大小寶寶節(jié)日快樂~~~~
更多技術(shù)文章,咱們公眾號(hào)見,我在公眾號(hào)里等你~
image.png
# -*- coding: utf-8 -*-
import os
import re
import threading
import time
from hashlib import md5
from urllib import urlencode
import requests
# 這里設(shè)置你想查詢的關(guān)鍵字
keyword = '美景'
# 這里替換成你自己的瀏覽器信息
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
# 頭條圖片搜索需要滑動(dòng)驗(yàn)證,因此簡(jiǎn)單處理,先手動(dòng)驗(yàn)證,然后設(shè)置cookie
cookie = 'tt_webid=6696746174420534791; WEATHER_CITY=%E5%8C%97%E4%BA%AC; UM_distinctid=16b0805ea6f31d-02830a8210d05a-37627e03-1fa400-16b0805ea705fd; tt_webid=6696746174420534791; __tasessionId=znvodagrm1559207733945; csrftoken=7201998104473d4e2ad8302bb74ae401; s_v_web_id=600eabfd649cb7a70f3d80b981411bfc; CNZZDATA1259612802=1444442826-1559202415-%7C1559207815'
headers = {
'Host': 'www.toutiao.com',
'Referer': 'https://www.toutiao.com/search/?keyword=' + keyword,
'User-Agent': user_agent,
'X-Requested-With': 'XMLHttpRequest',
'Cookie': cookie
}
start_offset = 0
end_offset = 20
step = 20
# 根據(jù)偏移量獲取每頁文章列表
def get_page_by_offset(offset):
params = {
'aid': '24',
'app_name': 'web_search',
'offset': offset,
'format': 'json',
'keyword': keyword,
'autoload': 'true',
'count': '20',
'en_qc': '1',
'cur_tab': '1',
'from': 'search_tab',
'pd': 'synthesis',
}
url = 'https://www.toutiao.com/api/search/content/?' + urlencode(params)
try:
resp = requests.get(url, headers=headers)
if resp.status_code == 200:
return resp.json()
except requests.ConnectionError:
return None
# 獲取每篇文章的重定向鏈接
def get_article_url(article):
if article.get('data'):
for item in article.get('data'):
article_url = item.get('article_url')
title = item.get('title')
yield {
'article_url': article_url,
'title': title
}
# 將圖片保存到文件
def save2file(title, url):
if not os.path.exists(title):
os.mkdir(title)
resp = requests.get(url)
file_name = './' + title + '/' + md5(resp.content).hexdigest() + '.jpg'
if not os.path.exists(file_name):
with open(file_name, 'wb') as f:
f.write(resp.content)
else:
print('Already Downloaded', file_name)
# 獲取每篇文章的圖片列表
def get_image_by_article(article):
article_url = article.get('article_url')
title = article.get('title')
print title
print article_url
if article_url:
try:
# 這里需要使用session的方式,否則會(huì)因?yàn)橹囟ㄏ虼螖?shù)太多而報(bào)錯(cuò)
session = requests.Session()
session.headers['User-Agent'] = headers['User-Agent']
resp = session.get(article_url)
if resp.status_code == 200:
# soup = BeautifulSoup(resp.text, 'lxml')
# result = soup.find_all(name='script')[6]
regex = '.*?img src="(.*?)".*?'
items = re.findall(regex, resp.text, re.S)
if items:
for item in items:
print item
save2file(title, item)
except requests.ConnectionError:
print 'Get image fail.'
if __name__ == '__main__':
for offset in range(start_offset, end_offset, step):
article_list = get_page_by_offset(offset)
for article in get_article_url(article_list):
# 每篇文章單獨(dú)起一個(gè)線程進(jìn)行抓取
t = threading.Thread(target=get_image_by_article(article))
t.start()
t.join()
# get_image_by_article(article)
end_time = time.time()
print('=====Done=====')
總結(jié)
以上是生活随笔為你收集整理的不用python爬今日头条_手把手教你从今日头条爬取你想要的任何图片的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3新式类_python新式类
- 下一篇: 前端电子表数字字体_爬虫:如何优雅应对字