美文网首页大数据 爬虫Python AI Sql大数据
Ajax异步加载:运用requests、BeautifulSou

Ajax异步加载:运用requests、BeautifulSou

作者: 夜希辰 | 来源:发表于2019-01-20 15:18 被阅读19次
Ajax异步加载:运用requests、BeautifulSoup爬取简书专题

第二篇爬虫项目实操:运用requests库、BeautifulSoup库爬取简书专题 ---- “数据蛙每周交作业小组”所有文章。按照惯例代码在文章结束部分,需要的同学可直接查看。

文章结构
一、爬虫学习心得
二、掌握的新知识
三、写爬虫中遇见的问题
四、代码部分《爬取“数据蛙每周交作业小组”所有文章》

一、爬虫学习心得

01爬虫与学习资料

前端时间找爬虫案例时看见一篇文章,里面汇总了“程序员专题”所有关于爬虫的文章,并按照喜欢数将文章从高到低排序,在写完这篇文章的时候我才恍然大悟其实那篇文章就是用爬虫写。
比如在用SQL查看“数据蛙每周交作业小组”专题爬取结果时,发现关于学习计划的文章阅读量是最高的(看来大家都喜欢明确的计划……),那我们可以运用爬虫写一篇文章汇总学习计划方面的文章。
当然爬取下来数据后,做分类和整理也是非常有必要的。爬虫=市调=向高手学习

02补充资料

附上两篇参考文章。数据分析实战---通过爬虫管理社群作业作业分析(一)——抄作业,写爬虫参考第一篇文章代码,结果分析参考文章二

二、掌握的新知识

01 Ajax异步加载

并不是所有的网页都是静态加载,即使有些网页看见它有分页的标志也也不一定是静态加载,需要看在跳转后面到页码时url是否发生变化,如艺龙就是有分页标志但是url不发生变化。

如果是异步加载需要查找分页的标志。首先查看每页数据数量,可直接传递url,解析html,返回的数量就是每页的数量。接着查看网页真实url:如图

02 数据隐藏

关于数据隐藏,这里分享两个案例。


html:简书爬取文章浏览量01 源代码:简书爬取文章浏览量08

案例一:筛选数据蛙文章阅读数和喜欢数。在通过find_all筛选标签的时候,返回了一个空的列表。这时候需要在源代码中去看属性。

查询详解:
 views_count = note['views_count']
 comments_count = note['comments_count']
 likes_count = note['likes_count']

如果在源代码中可以看见相应的标签 那么恭喜你。如果在源代码中标签的值为0,具体解决方法我也不知道,上次在爬取58同城浏览数和申请书就遇见类似的问题。


html:58浏览量 源代码:58浏览量
03 list out of rang

list out of range是一种错误方式。主要有两个原因返回空值,标签选择错误。如果是返回了一个空值,就需要检查标签选择是否正确;如果标签正确一句返回空值,就需要查看HTML里面的某些标签是否被隐藏,我们在HTML里面的标签看的见但筛选不出来的时就需要查看网页源代码,并在源代码里面查看标签和属性。

04 网页链接

网页链接在网址上查看,不要偷懒。


href 详情页url

比如关于详情页的url,我想直接从a标签下的href。而a标签里面的href只定义的一部分。

三、写爬虫中遇见的问题

这里分享一个问题'NavigableString' object has no attribute 'find_all'

def parse_one_page(html):
    soup = BeautifulSoup(html,'lxml')
    content_li = soup.find_all('ul',class_ = 'note-list')[0].find_all("li")
    dir = {}
    for link in content_li:
        url = link.find_all('a',class_ = 'title')[0]
        href = url['href']
        #title = link.find_all('a',class_ = 'title')[0].text
        title = url.text
        link="https://www.jianshu.com"+url.get("href")
        dir[link] = title
    return dir

因为自己为了偷懒,想一步到位将content_li 合并在一起,结果直接报错,而且无论如何百度都没有找出原因。后来将content_li 分开写就运行成功。

note_list拆开后不再报错
note_list = soup.find_all('ul',class_ = 'note-list')[0]
content_li = note_list.find_all("li")

具体原因我也不知道只知道运行成功了,如果有人知道希望能指点一二

四、代码部分《爬取“数据蛙每周交作业小组”所有文章》

01 爬取目标站点
简书数据蛙专题
数据分析实战---通过爬虫管理社群作业: https://www.jianshu.com/c/af12635a5aa3
02爬取内容

昵称name,标题title,文章字数word_age,文章阅读数views_count,文章喜欢数likes_count,文章评论数comments_count,文章创建时间publish_time,总字数total_wordage,关注数followers_count,总喜欢数total_likes_count

03 代码
部分爬取结果
# 爬取目标《数据蛙每周交作业小组》
# 索引页标题、跳转详情页链接
# 详情页用户名、提交时间、字数、阅读数、喜欢数
# 异步加载内容

import pymysql
import requests
import json
from bs4 import BeautifulSoup
from requests.exceptions import RequestException

headers = {'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"}
def get_one_page(url):
    try:
        respones = requests.get(url,headers = headers)
        respones.encoding = 'utf-8'
        if respones.status_code == 200:
            return respones.text
        return None
    except RequestException:
        print('请求索引页错误')
        return None

def parse_one_page(html):
    soup = BeautifulSoup(html,'lxml')
    note_list = soup.find_all('ul',class_ = 'note-list')[0]
    content_li = note_list.find_all("li")
    dir = {}
    for link in content_li:
        url = link.find_all('a',class_ = 'title')[0]
        href = url['href']
        #title = link.find_all('a',class_ = 'title')[0].text
        title = url.text
        link="https://www.jianshu.com"+url.get("href")
        dir[link] = title
    return dir

def get_two_page(url):
    try:
        respones=requests.get(url,headers=headers)#get请求
        if respones.status_code==200:
            return respones.text
        return None
    except RequestException:
        print("请求详情页有错误")
        return None

def parse_two_page(title,html):
    title=title
    soup = BeautifulSoup(html, 'html.parser')
    name = soup.find_all('div',class_ = 'info')[0].find_all('span',class_ = 'name')[0].text
    publish_time = soup.find_all('div',class_ = 'meta')[0].find_all('span',class_ = 'publish-time')[0].text
    word_age = soup.find_all('div',class_ = 'meta')[0].find_all('span',class_ = 'wordage')[0].text

    note_list = soup.find_all("script", type="application/json")[0].contents[0]
    note_list = json.loads(note_list)
    note = note_list['note']
    views_count = note['views_count']
    comments_count = note['comments_count']
    likes_count = note['likes_count']
    author = note['author']
    total_wordage = author['total_wordage']
    followers_count = author['followers_count']
    total_likes_count = author['total_likes_count']

    return name,title,word_age,views_count,likes_count,comments_count,publish_time,total_wordage,followers_count,total_likes_count

def save_to_mysql(name,title,word_age,views_count,likes_count,comments_count,publish_time,total_wordage,followers_count,total_likes_count):
    cur = conn.cursor()   #用来获得python执行Mysql命令的方法,操作游标。cur = conn.sursor才是真的执行
    insert_data = "INSERT INTO jianshu(name,title,word_age,views_count,likes_count,comments_count,publish_time,total_wordage,followers_count,total_likes_count)" "VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    val = (name,title,word_age,views_count,likes_count,comments_count,publish_time,total_wordage,followers_count,total_likes_count)
    cur.execute(insert_data, val)
    conn.commit()

conn=pymysql.connect(host="localhost",user="root", password='18030823940',db='58yuesao',port=3306, charset="utf8")

def main():
    urls = ['https://www.jianshu.com/c/af12635a5aa3?order_by=added_at&page={}'.format(i) for i in range(1, 37)]
    for url in urls:
        html = get_one_page(url)
        dir = parse_one_page(html)
        for link, title in dir.items():
            html = get_two_page(link)
            name, title, word_age, views_count, likes_count, comments_count, publish_time, total_wordage, followers_count ,total_likes_count= parse_two_page(title, html)
            save_to_mysql(name,title,word_age,views_count,likes_count,comments_count,publish_time,total_wordage,followers_count,total_likes_count)

if __name__ =='__main__':
    main()

爬虫学习先告一段落以后在工作中在进一步精进,周一周二刷python和SQL的练习题,周三开始学习机器学习模型。

相关文章

网友评论

    本文标题:Ajax异步加载:运用requests、BeautifulSou

    本文链接:https://www.haomeiwen.com/subject/dvmxjqtx.html