美文网首页Python爬虫作业Python3自学 爬虫实战
爬虫日记---小白自学知识点记录(记七日热点)

爬虫日记---小白自学知识点记录(记七日热点)

作者: 狗妈妈2 | 来源:发表于2017-04-24 17:41 被阅读137次

先开始说一段废话吧。。。
我是从3月中旬开始接触Python。当时我想学习如何去做出比较专业的数据分析图,然后我家人说R语言和Python都可以做出图来。但他建议学Python。我在网上找学习的资料,偶尔之间看到python可以实现爬虫功能。正如彭老师的简书中写到的“学习Python,比较好快速找到应用的场景”。看到爬虫取得各个网页大数据后做的数据分析,这也是我学习的兴趣所在。学习过程饶了不少弯路,以下是我自己的一些教训吧。

python语言学习经验:

1、基础知识要扎实,先要学习一些python的基本操作
参考一本《简明 Python 教程》的文章,因为学过C语言,有些编程的基本常识,所以着重看了些:

      1)数据结构(列表,元组,字典)
      2)控制流(if,for,try...except)
      3)函数(变量,参数,实参,形参,参数的传递)
      4)类

这些在爬虫中反复应用到,一定要学习扎实,不要一开始就去找别人做的爬虫案例。先把基础知识点过一遍,至少知道python的语言结构是怎么样的。会打python代码

2、了解爬虫的原理。学习哪些关键知识点
我的经验是先了解html的网页代码,再搞清楚爬虫的过程,然后一个一个知识点去查资料,去练习。可以在终端先从几行小代码开始练习。最后在做一个小爬虫,然后慢慢变大爬虫,哈哈。。。。(我之前就是没有搞清楚怎么入手学爬虫,饶了一圈回到原点)

爬虫的抓取过程:

先获得网页地址----〉解析网页代码----〉抓取和提取网页内容---〉存储数据      是不是很简单。。。。

小爬虫变大爬虫:

单页爬虫----〉多页爬虫----〉“迭代”爬虫(就是有爬取链接页面底下的页面)----〉异步加载爬虫---〉scrapy爬虫(目前正在攻克中。。。)

爬虫的小知识点主要在于抓取和提取网页内容:

1)BeatifulSoup

说到这个“美丽汤“,我真是又爱又恨。我第一次在终端用的时候就不能运行。大受打击。原因是引入这个类的时候没有区分大小
 错误:
from bs4 import beautifulsoup
正确:
from bs4 import BeautifulSoup
#bs4是一个python的库,BeautifulSoup是这个库里的一个类

知识点1:
soup.find_all('tag.name', class_='class_ value')
soup.find_all('tag.name',attrs ={'class':'class_ value'})

举例:
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story"><a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html_doc)
print soup.find_all('title')  #提取'title'标签的所有列表
print soup.find_all('p',class_='title') #提取含‘p'标签的且'class'属性是'title'的所有列表
print soup.find_all('a')  #提取'a'标签的所有列表
print soup.find_all(id="link2") #提取id的'属性是"link2"的所有列表

返回值为:
[<title>The Dormouse's story</title>]
[<p class="title"><b>The Dormouse's story</b></p>]
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

知识点2:
soup.select(tag.name1 tag.name2 tag.name3) #提取tag.name1标签下的tag.name2标签下的tag.name3的列表
soup.select('#****')
soup.select('.****')
soup.select('tag.name #***')
举例:
soup.select('#sponsor') #通过id查找,搜索 id 为 sponsor 的标签列表
#可以在chrome网页抓包中点击你要抓的那个tag,看到整个tag的层次(见图“抓包tag“)

soup.select('.ebox')   .这个点表示查询class="ebox"的,所有标签内容
soup.select('div #index_nav')  表示寻找div标签中id为index_nav的标签内容。

为了方便查找自己抓取的内容,以上可以把空格改为' 〉':
举例:
soup.select("div > #index_nav")
抓包tag
  1. Xpath知识点
·在网页源代码中右键,Copy XPath

·// 定位根节点

·/ 往下层寻找

·提取文本内容:/text()

·提取属性内容: /@xxxx

·以相同的字符开头 starts-with(@属性名称, 属性字符相同部分)

·标签套标签 string(.)

3)正则表达式
目前我还不是很会,所以不做描述

开始爬啦--爬取“简书7日热门“

我在这里就不做具体讲解,可以看一下其他童鞋在爬虫作业专题做的作业,就我犯得一些错误和大家分享一下吧

#-*-coding:'utf-8'-*-
import requests
from lxml import etree
import csv
import re
import json
import sys
reload(sys)
sys.setdefaultencoding('utf8')
base_url='http://www.jianshu.com/'

def information(url):

    html=requests.get(url).content
    selector=etree.HTML(html)
    datas=selector.xpath('//ul[@class="note-list"]/li')
    infos=[]
    for data in datas:
        detail_url=data.xpath('a/@href')
        if detail_url:
            detail_url1=detail_url[0]
            detail_url1='http://www.jianshu.com'+detail_url1
            info=information2(detail_url1)
            infos.append(info)
    return infos

def information2(url):
    info=[]
    html=requests.get(url).content
    selector=etree.HTML(html)
    user=selector.xpath('//span[@class="name"]/a/text()')[0]
    title=selector.xpath('//div[@class="article"]/h1[@class="title"]/text()')[0]
    #read_qty = selector.xpath('//div[@class="meta"]/span[2]/text()')[0]
    #read_qty=re.findall('"views_count":(.*?),', html, re.S)[0]
    view_qty=re.findall('"views_count":(.*?),', html, re.S)[0]
    comment_qty=re.findall('"comments_count":(.*?),', html, re.S)[0]
    like_qty=re.findall('"likes_count":(.*?),', html, re.S)[0]
    id=re.findall('"id":(.*?),', html, re.S)[0]
    reward_url='http://www.jianshu.com/notes/%s/rewards?count=20' %id
    html_reward=requests.get(reward_url).text
    reward_detail=json.loads(html_reward)
    reward_qty=reward_detail['rewards_count']
    html_collection_url='http://www.jianshu.com/notes/%s/included_collections?page=1' %id
    collection=collections(html_collection_url,id)
    info.append(user)
    info.append(title)
    info.append(view_qty)
    info.append(comment_qty)
    info.append(like_qty)
    info.append(reward_qty)
    info.append(collection)
    return info

def collections(url,id):
    html=requests.get(url).content
    collection_detail=json.loads(html)
    pages=collection_detail['total_pages']
    collection_urls=['http://www.jianshu.com/notes/{}/included_collections?page={}'.format(id,str(i)) for i in range(1,pages+1)]
    datas = []
    for url in collection_urls:
        html_collection=requests.get(url).content
        collection_detail=json.loads(html_collection)
        for one in collection_detail['collections']:
            datas.append(one['title'])
    data=','.join(datas)
    return(data)

if __name__=='__main__':
    urls=["http://www.jianshu.com/trending/weekly?&page={}".format(i) for i in range(1,27)]
    csvfile=file('sevenday.csv','wb')
    writer=csv.writer(csvfile)
    #infos=[]
    for url in urls:
        resources=information(url)
        #infos.append(resoure)
        for resource in resources:
            writer.writerow(resource)
    csvfile.close()

每一个小程序都是在不断的调试不断的查资料中进行的。
错误1:(印象也是最深刻的)
对xpath的抓数据理解不够透彻,我想要抓取的是首页的每个标题的链接,看一下网页代码:

Paste_Image.png

分析:每一个href都存放在a标签下,a标签又存放在div.content下,思路:把所有li都提取到。然后for循环爬取li下的a下的href信息。(具体可以看图片底部的标签name)。我们可以按照以下来做:

datas=selector.xpath('//ul[@class="note-list"]/li')
for data in datas:
   detail_url=data.xpath('a/@href')

我当时写成了:

datas=selector.xpath('//div[@class="list-container"]/ul[@class="note-list"]')
for data in datas:
    detail_url=data.xpath('li/a/@href')

经过测试len[datas]结果是0,原因是其实提取了ul下满足class="note-list"的标签。并没有爬取到li这一层

错误2:提取分页链接的url时候,发现程序一直出现报错。
教训:需要学会调试,从大的范围开始调试,在一点缩小范围,找出问题所在
print 所有的 detail_url时候发现,有的url为空,故需要做一个判断是否为空。

for data in datas:
   detail_url=data.xpath('a/@href')
   if detail_url:
       detail_url1=detail_url[0]

总结

谢谢程老师彭老师的指导帮助!
还有就是多看!多想!多问!最重要的是多做!!!

相关文章

  • 爬虫日记---小白自学知识点记录(记七日热点)

    先开始说一段废话吧。。。我是从3月中旬开始接触Python。当时我想学习如何去做出比较专业的数据分析图,然后我家人...

  • 爬虫日记---七日热点scrapy版

    受大牛们的鼓励,继2个熬夜的晚上终于做完scrapy版的“七日热点”。宝宝好累,做到凌晨,电脑差一点被收走。 赶紧...

  • 柒日記·柒

    二零一九年十一月二十一日,七日记,七。 终于来到了七日记第七篇,好好的日记生生被自己拖成了月记。 拆迁……终于等来...

  • 小白自学记

  • 柒日記·叁

    二零一九年十月二十八日,七日记,三。 七日记中断数日。这几天去过户了属于自己的公司,至于为什么开公司,则是为了变相...

  • 绘画小白自学记录

    在图书馆工作,除小时喜欢在书本空白处胡乱涂画,由于种种原因到今年差不多三十年没摸过画笔。前段时间偶然浏览简书手绘和...

  • 禅七日记

    禅七日记六 ——痴癫山人 六,闭关禅修 (三)当家师 二十七日,虽然不停折腾,但还坚持...

  • 7.爬虫概述

    爬虫概述 知识点: 了解 爬虫的概念 了解 爬虫的作用 了解 爬虫的分类 掌握 爬虫的流程 1. 爬虫的概念 模拟...

  • 小爬虫

    注:本人菜鸟一枚,自学python,记录学习过程中所学所思,希望自己有所收获 总结:涉及面向对象(self)、爬虫...

  • 我的素描之路

    谨以此记录从一个素描小白的成长记!

网友评论

    本文标题:爬虫日记---小白自学知识点记录(记七日热点)

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