python爬虫今日头条街拍美图开发背景_分析Ajax请求并抓取今日头条街拍美图:爬取详情页的url与实际页面上显示不符...
from urllib.parse import urlencode
import re
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
import requests
import json
def get_page_index(offset,keyword):#定義一個函數(shù)用于獲取索引頁信息
data = {
'offset': offset,
'format': 'json',
'keyword': keyword,
'autoload': 'true',
'count': '20',
'cur_tab': '3'
}
# cur_tab為3指的是圖集板塊,數(shù)過來第三個,若為1則指代綜合板塊
#count 數(shù)量
url = 'http://www.toutiao.com/search_content/?' + urlencode(data) #urlencode可將字典對象轉(zhuǎn)化為url的請求參數(shù)
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
try:
response = requests.get(url,headers=headers)
if response.status_code == 200:
return response.text
else:
return None
except RequestException:
print('請求索引頁出錯')
return None
def parse_page_index(html):#定義一個函數(shù)解析索引頁信息,返回一個包含詳情頁url的迭代器
data = json.loads(html)#將字符串轉(zhuǎn)化為一個對象(字典)
if data and 'data' in data.keys():#判斷data是否為空,同時要滿足鍵里面有‘data’
for item in data.get('data'):#獲取字典中key為‘data’的對應(yīng)的值,這個值data.get('data')為一個容量為20的列表,列表的元素為字典
yield item.get('article_url')#獲取字典中key為‘a(chǎn)rticle_url’的對應(yīng)的值,即網(wǎng)址
def get_page_detail(url):#定義一個函數(shù)用于得到詳情頁下的信息
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
return None
except RequestException:
print('請求詳情頁出錯')
return None
def parse_page_detail(html):#定義解析詳情頁的方法
soup = BeautifulSoup(html,'lxml')
title = soup.select('title')[0].get_text()
print(title)
'''
image_pattern = re.compile('gallery: (.*?),\n? ? siblingList',re.S)
result = re.search(image_pattern,html)
if result:
print(result.group(1))
'''
def main():
html = get_page_index('0','街拍')
for url in parse_page_index(html):#parse_page_index(html)返回的是一個迭代器,每次輸出一個網(wǎng)址
print(url)
html = get_page_detail(url)
if html:
parse_page_detail(html)
#print(url)
if __name__ == '__main__':
main()
總結(jié)
以上是生活随笔為你收集整理的python爬虫今日头条街拍美图开发背景_分析Ajax请求并抓取今日头条街拍美图:爬取详情页的url与实际页面上显示不符...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 下pg负载均衡_SAE 场景下,应用流量
- 下一篇: 领了发票后税盘里没有怎么办