Python今日头条网爬虫

encoding=utf8

import requests
from requests.exceptions import RequestException
import urllib
import json
import re
from bs4 import BeautifulSoup
from config import *
def get_index(offset,keyword):
data={
'offset':offset,
'format':'json',
'keyword':keyword,
'autoload':'true',
'count':20,
'cur_tab':3
}
url='http://www.toutiao.com/search_content/?'+urllib.urlencode(data)
response=requests.get(url)
try:
if response.status_code == 200:
return response.text
return None
except RequestException:
print u'请求索引页出错'
return None
def parse_page_index(html):
#将json格式的字符串转化成python对象,对象转换成json用 json.dumps()
data=json.loads(html)
if data and 'data' in data.keys():
for item in data.get('data'):
#yield 是url生成器 即取出article_url并生成url
yield item.get('article_url')
def get_page_detail(url):
response = requests.get(url)
try:
if response.status_code == 200:
return response.text
return None
except RequestException:
print '请求详情页出错'
return None
def parse_page_detail(html,url):
soup=BeautifulSoup(html,'lxml')
title = soup.select('title')[0].get_text()
images_pattern= re.compile('var gallery = (.*?);',re.S)
result = re.search(images_pattern,html)
if result:
data =json.loads(result.group(1))
sub_images = data.get('sub_images')
images = [item.get('url') for item in sub_images]
return {
'title' :title,
'url':url,
'images':images
}
def main():
html=get_index(0,'街拍')
for url in parse_page_index(html):
html=get_page_detail(url)
if html:
result=parse_page_detail(html,url)
print result['title']
if name == 'main':
main()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文是学习 天善学院 Python3爬虫三大案例实战分享 / 分析Ajax抓取今日头条街拍美图 后所写,感谢崔庆才...
    4ffde5305e8f阅读 1,858评论 0 5
  • 1 前言 作为一名合格的数据分析师,其完整的技术知识体系必须贯穿数据获取、数据存储、数据提取、数据分析、数据挖掘、...
    whenif阅读 18,113评论 45 523
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,067评论 19 139
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 8,930评论 0 6
  • 看了两季的《我们来了》(上季叫《偶像来了》,尽管又是一舶来品,但还是有看点的),最大的亮点其实还是谢娜,她总是那个...
    Bemine阅读 294评论 0 0