本文章是对网易云课堂中的Python网络爬虫实战课程进行总结。感兴趣的朋友可以观看视频课程。课程地址

爬虫简介

一段自动抓取互联网信息的程序

非结构化数据

没有固定的数据格式,如网页资料。
必须通过ETL(Extract,Transformation,Loading)工具将数据转化为结构化数据才能使用。

工具安装

Anaconda

pip install requests
pip install BeautifulSoup4
pip install jupyter

打开jupyter

jupyter notebook

requests 网络资源截取插件

取得页面

import requests
url = ''
res = requests.get(url)
res.encoding = 'utf-8'
print (res.text)

将网页读进BeautifulSoup中

from bs4 import BeautifulSoup
soup = BeautifulSoup(res.text, 'html.parser')
print (soup.text)

使用select方法找找出特定标签的HTML元素,可取标签名或id,class返回的值是一个list

select('h1')   select('a')
id = 'thehead' select('#thehead') alink = soup.select('a')
for link in alink:
print (link['href'])

例子

  • 1、取得新浪陕西的新闻时间标题和连接

    import requests
    from bs4 import BeautifulSoup
    res = requests.get('http://sx.sina.com.cn/')
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser') for newslist in soup.select('.news-list.cur'):
    for news in newslist:
    for li in news.select('li'):
    title = li.select('h2')[0].text
    href = li.select('a')[0]['href']
    time = li.select('.fl')[0].text
    print (time, title, href)
  • 2、获取文章的标题,来源,时间和正文

    import requests
    from bs4 import BeautifulSoup
    from datetime import datetime
    res = requests.get('http://sx.sina.com.cn/news/b/2018-06-02/detail-ihcikcew5095240.shtml')
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser') h1 = soup.select('h1')[0].text
    source = soup.select('.source-time span span')[0].text
    timesource = soup.select('.source-time')[0].contents[0].text
    date = datetime.strptime(timesource, '%Y-%m-%d %H:%M') article = []
    for p in soup.select('.article-body p')[:-1]:
    article.append(p.text.strip()) ' '.join(article)

    简写为:

    ' '.join([p.text.strip() for p in soup.select('.article-body p')[:-1]])

    说明:

    datatime 包用来格式化时间
    [:-1]去除最后一个元素
    strip() 移除字符串头尾指定的字符(默认为空格或换行符)
    ' '.join(article) 将列表以空格连接
  • 3、获取文章的评论数,评论数是通过js写入,不能通过上面的方法获取到,在js下,找到文章评论的js

    import requests
    import json comments = requests.get('http://comment5.news.sina.com.cn/cmnt/count?format=js&newslist=sx:comos-hcikcew5095240:0')
    jd = json.loads(comments.text.strip('var data =')) jd['result']['count']['sx:comos-hcikcew5095240:0']['total']
  • 4、将获得评论的方法总结成一个函数

    import re
    import json commenturl = 'http://comment5.news.sina.com.cn/cmnt/count?format=js&newslist=sx:comos-{}:0' def getCommentCounts(url):
    m = re.search('detail-i(.+).shtml' ,url)
    newsid = m.group(1)
    comments = requests.get(commenturl.format(newsid))
    jd = json.loads(comments.text.strip('var data ='))
    return jd['result']['count']['sx:comos-'+newsid+':0']['total'] news = 'http://sx.sina.com.cn/news/b/2018-06-01/detail-ihcikcev8756673.shtml'
    getCommentCounts(news)
  • 5、输入地址得到文章的所有信息(标题、时间、来源、正文等)的函数(完整版)

    import requests
    import json
    import re
    from bs4 import BeautifulSoup
    from datetime import datetime commenturl = 'http://comment5.news.sina.com.cn/cmnt/count?format=js&newslist=sx:comos-{}:0' def getCommentCounts(url):
    m = re.search('detail-i(.+).shtml' ,url)
    newsid = m.group(1)
    comments = requests.get(commenturl.format(newsid))
    jd = json.loads(comments.text.strip('var data ='))
    return jd['result']['count']['sx:comos-'+newsid+':0']['total'] def getNewsDetail(newsurl):
    result = {}
    res = requests.get(newsurl)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    result['title'] = soup.select('h1')[0].text
    result['newssource'] = soup.select('.source-time span span')[0].text
    timesource = soup.select('.source-time')[0].contents[0].text
    result['date'] = datetime.strptime(timesource, '%Y-%m-%d %H:%M')
    result['article'] = ' '.join([p.text.strip() for p in soup.select('.article-body p')[:-1]])
    result['comments'] = getCommentCounts(newsurl)
    return result news = 'http://sx.sina.com.cn/news/b/2018-06-02/detail-ihcikcew8995238.shtml'
    getNewsDetail(news)

Python爬虫初识的更多相关文章

  1. 孤荷凌寒自学python第六十七天初步了解Python爬虫初识requests模块

    孤荷凌寒自学python第六十七天初步了解Python爬虫初识requests模块 (完整学习过程屏幕记录视频地址在文末) 从今天起开始正式学习Python的爬虫. 今天已经初步了解了两个主要的模块: ...

  2. Python爬虫--初识爬虫

    Python爬虫 一.爬虫的本质是什么? 模拟浏览器打开网页,获取网页中我们想要的那部分数据 浏览器打开网页的过程:当你在浏览器中输入地址后,经过DNS服务器找到服务器主机,向服务器发送一个请求,服务 ...

  3. @1-2初识Python爬虫

    初识Python爬虫 Python爬虫(入门+进阶)     DC学院 环境搭建: Python2与Python3的差异:python2与python3整体差异不大,大多是一些语法上的区别,考虑到py ...

  4. 初识python爬虫框架Scrapy

    Scrapy,按照其官网(https://scrapy.org/)上的解释:一个开源和协作式的框架,用快速.简单.可扩展的方式从网站提取所需的数据. 我们一开始上手爬虫的时候,接触的是urllib.r ...

  5. 初识Python和使用Python爬虫

     一.python基础知识了解:   1.特点: Python的语言特性: Python是一门具有强类型(即变量类型是强制要求的).动态性.隐式类型(不需要做变量声明).大小写敏感(var和VAR代表 ...

  6. 【Python爬虫】BeautifulSoup网页解析库

    BeautifulSoup 网页解析库 阅读目录 初识Beautiful Soup Beautiful Soup库的4种解析器 Beautiful Soup类的基本元素 基本使用 标签选择器 节点操作 ...

  7. python爬虫系列序

    关于爬虫的了解,始于看到这篇分析从数据角度解析福州美食,和上份工作中的短暂参与. 长长短短持续近一年的时间,对其态度越来越明晰,噢原来这就是我想从事的工作. 于是想要系统学习的心理便弥散开来…… 参考 ...

  8. python 爬虫简介

    初识Python爬虫 互联网 简单来说互联网是由一个个站点和网络设备组成的大网,我们通过浏览器访问站点,站点把HTML.JS.CSS代码返回给浏览器,这些代码经过浏览器解析.渲染,将丰富多彩的网页呈现 ...

  9. Python正则表达式初识(二)

    前几天给大家分享了Python正则表达式初识(一),介绍了正则表达式中的三个特殊字符“^”.“.”和“*”,感兴趣的伙伴可以戳进去看看,今天小编继续给大家分享Python正则表达式相关特殊字符知识点. ...

随机推荐

  1. 918. Maximum Sum Circular Subarray

    Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty ...

  2. Hash Table-720. Longest Word in Dictionary

    Given a list of strings words representing an English Dictionary, find the longest word in words tha ...

  3. C++中new申请动态数组

    C++中数组分为静态数组和动态数组,静态数组必须确定数组的大小,不然编译错误:而动态数组大小可以不必固定,用多少申请多少.静态数组类于与我们去餐馆吃饭,餐馆会把菜做好.而动态数组类似于我们自己买菜做饭 ...

  4. webpack快速入门——实战技巧:webpack模块化配置

    首先在根目录,新建一个webpack_config文件夹,然后新建entry_webpack.js文件,代码如下: const entry ={}; //声明entry变量 entry.path={ ...

  5. Git进行fork后如何与原仓库同步

    在进行Git协同开发的时候,往往会去fork一个仓库到自己的Git中,过一段时间以后,原仓库可能会有各种提交以及修改,很可惜,Git本身并没有自动进行同步的机制,这个需要手动去执行.name如何进行自 ...

  6. Jvm内存工具

    1,JConsole  位于 [JDK] bin 下, 2,代码查看当前进程堆内存 long maxMemory = Runtime.getRuntime().maxMemory();long tot ...

  7. Web开发常用在线工具

    http://tool.oschina.net/ 爬去网页工具: http://www.keydatas.com/product

  8. Git-基本操作(图文)

    场景一: 已经用git add 命令把文件加入到暂存区了,这个时候想退回怎么办? 添加文件到暂存区 :git add . 将单个文件撤回到工作区:git rm --cached [文件路径] 将目录撤 ...

  9. Android 开发服务类 02_NewsListServlet

    Servlet implementation class NewsListServlet package com.wangjialin.server.xml; import java.io.IOExc ...

  10. 极高效内存池实现 (cpu-cache)

    视频请看 : http://edu.csdn.net/course/detail/627 1.内存池的目的 提高程序的效率 减少运行时间 避免内存碎片 2.原理   要解决上述两个问题,最好的方法就是 ...