分析Ajax请求抓取今日头条街拍美图
来源:互联网 发布:vs2013能做php开发吗 编辑:程序博客网 时间:2024/05/15 05:44
有一些网页直接请求得到的HTML代码并没有在网页中看到的内容,因为一些信息是通过Ajax加载,并通过js渲染生成的,这时就需要通过分析网页的请求来获取想要爬取的内容。通过抓取今日头条街拍美图讲解一下具体操作步骤。
首先打开今日头条网页,搜索街拍
选择图集,抓取组图
使用开发人员工具,查看网页html代码
发现并没有想要的内容信息,接下来查看Ajax请求,注意我拿红圈圈出来的地方
查看Ajax请求url以及请求的方法,发现是用get方法,所以使用requests库
查看Ajax请求参数
查看详情页的内容
代码
import requestsfrom urllib.parse import urlencodefrom requests.exceptions import RequestExceptionimport jsonfrom bs4 import BeautifulSoupimport re#获得通过Ajax请求的到的html代码def get_page_index(offset,keyword): query_parameters = { 'offset': offset, 'format': 'json', 'keyword': keyword, 'autoload': 'true', 'count': '20', 'cur_tab': 3 }#Ajax请求参数 url ='http://www.toutiao.com/search_content/?' + urlencode(query_parameters)#Ajax请求url response = requests.get(url) try: if response.status_code == 200: return response.text return None except RequestException: print('请求索引页失败') return None#获得图集的urldef parse_page_index(parse_index_html): data = json.loads(parse_index_html) if data and 'data' in data.keys(): for item in data.get('data'): yield item.get('article_url')#通过yield将函数变作一个生成器#获得页面的详细内容def get_page_detail(get_detail_url): response = requests.get(get_detail_url) try: if response.status_code == 200: return response.text return None except RequestException: print('请求详情页失败',url) return None#解析详情页def parse_page_detail(html,url): soup = BeautifulSoup(html,'lxml') title = soup.select('title')[0].get_text() print(title) images_pattern = re.compile('var gallery = (.*?);',re.S) result = re.search(images_pattern,html) if result: data = json.loads(result.group(1)) if data and 'sub_images' in data.keys(): 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_page_index(0,'街拍') for url in parse_page_index(html): html = get_page_detail(url) if html: result = parse_page_detail(html,url) print(result)if __name__ == '__main__': main()
运行结果
注:可能讲解有出错的地方,望大家看到能给指正,一块交流学习。博主现在准备复习考研,时间不是很多,并没有写如何把图片存到本地的代码,以后有时间了再继续完善。
1 0
- 分析Ajax请求抓取今日头条街拍美图
- 分析AJAX抓取今日头条街拍美图(上)
- 分析AJAX抓取今日头条街拍美图(下)
- 分析AJAX抓取今日头条街拍美图(存储)
- Python爬虫-分析Ajax抓取今日头条街拍美图
- ajax动态抓取今日头条街拍美图
- 分析Ajax请求并爬取下载今日头条街拍美图
- requests分析Ajax来爬取今日头条街拍美图
- scrapy抓取ajax请求的网页
- scrapy 抓取ajax请求的网页-以ifanr为例
- 使用python3分析Ajax爬取今日头条上的街拍美图
- python爬今日头条(ajax分析)
- 抓取今日头条文章
- 抓取今日头条新闻
- 利用iframe实现ajax跨域请求,抓取网页中ajax数据
- ajax请求的异步嵌套问题分析
- ajax请求的异步嵌套问题分析
- 封装Ajax请求,callback函数参数分析
- IOS 教程:自定义链接下载应用并直接安装ipa-itms-services
- 综合里dont_use/dont_touch/ideal_network的理解
- JAVA变量,数据类型及转换,
- 子树
- 遍历字符串
- 分析Ajax请求抓取今日头条街拍美图
- 牛客网算法课程优惠码
- 用svg制作圆形进度条动画效果 js 并且能监听滚动条百分比
- 关于WebView不能加载网页,配置,兼容适配问题
- tomcat报错org.springframework.web.context.ContextLoaderListener
- C#学习笔记(1)
- 软件测试过程
- 循环里面嵌套一个异步请求,所有循环执行完毕后再返回请求的数据
- spring配置文件根据环境选取