Python爬虫初识
本文章是对网易云课堂中的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爬虫初识的更多相关文章
- 孤荷凌寒自学python第六十七天初步了解Python爬虫初识requests模块
孤荷凌寒自学python第六十七天初步了解Python爬虫初识requests模块 (完整学习过程屏幕记录视频地址在文末) 从今天起开始正式学习Python的爬虫. 今天已经初步了解了两个主要的模块: ...
- Python爬虫--初识爬虫
Python爬虫 一.爬虫的本质是什么? 模拟浏览器打开网页,获取网页中我们想要的那部分数据 浏览器打开网页的过程:当你在浏览器中输入地址后,经过DNS服务器找到服务器主机,向服务器发送一个请求,服务 ...
- @1-2初识Python爬虫
初识Python爬虫 Python爬虫(入门+进阶) DC学院 环境搭建: Python2与Python3的差异:python2与python3整体差异不大,大多是一些语法上的区别,考虑到py ...
- 初识python爬虫框架Scrapy
Scrapy,按照其官网(https://scrapy.org/)上的解释:一个开源和协作式的框架,用快速.简单.可扩展的方式从网站提取所需的数据. 我们一开始上手爬虫的时候,接触的是urllib.r ...
- 初识Python和使用Python爬虫
一.python基础知识了解: 1.特点: Python的语言特性: Python是一门具有强类型(即变量类型是强制要求的).动态性.隐式类型(不需要做变量声明).大小写敏感(var和VAR代表 ...
- 【Python爬虫】BeautifulSoup网页解析库
BeautifulSoup 网页解析库 阅读目录 初识Beautiful Soup Beautiful Soup库的4种解析器 Beautiful Soup类的基本元素 基本使用 标签选择器 节点操作 ...
- python爬虫系列序
关于爬虫的了解,始于看到这篇分析从数据角度解析福州美食,和上份工作中的短暂参与. 长长短短持续近一年的时间,对其态度越来越明晰,噢原来这就是我想从事的工作. 于是想要系统学习的心理便弥散开来…… 参考 ...
- python 爬虫简介
初识Python爬虫 互联网 简单来说互联网是由一个个站点和网络设备组成的大网,我们通过浏览器访问站点,站点把HTML.JS.CSS代码返回给浏览器,这些代码经过浏览器解析.渲染,将丰富多彩的网页呈现 ...
- Python正则表达式初识(二)
前几天给大家分享了Python正则表达式初识(一),介绍了正则表达式中的三个特殊字符“^”.“.”和“*”,感兴趣的伙伴可以戳进去看看,今天小编继续给大家分享Python正则表达式相关特殊字符知识点. ...
随机推荐
- 670. Maximum Swap
Given a non-negative integer, you could swap two digits at most once to get the maximum valued numbe ...
- myeclipse注册码生成
import java.io.*; /** * <一句话功能简述> * <功能详细描述> * * @author 程松 * @date 2013-11-8上午8:50:34 * ...
- 【wireshark】协议解析
1. 普通解析 Wireshark启动时,所有解析器进行初始化和注册.要注册的信息包括协议名称.各个字段的信息.过滤用的关键字.要关联的下层协议与端口(handoff)等.在解析过程,每个解析器负责解 ...
- out.print()与out.write()的区别
out对象的类型是JspWriter.JspWriter继承了java.io.Writer类. 1)print方法是子类JspWriter,write是Writer类中定义的方法: 2)重载的prin ...
- Python3模块: hashlib
简介: 用于加密相关的操作,代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法. 在python3中已经废弃了md5和sha模块,简单说 ...
- Python绑定方法与非绑定方法
绑定方法 绑定方法(绑定给谁,谁来调用就自动将它本身当作第一个参数传入): 绑定到类的方法:用classmethod装饰器装饰的方法,类在使用时会将类本身当做参数传给类方法的第一个参数(即便是对象来调 ...
- Swift 使用 #warning
swift 中没法使用#Warning来提示警告, 可以通过给TODO: FIXME:加上警告, 实现类似的效果. Build Phases ---> Run Script ---> ad ...
- rabbitmq使用日记
一.安装 添加安装源 #echo 'deb http://www.rabbitmq.com/debian/ testing main' | sudo tee /etc/apt/sources.list ...
- LODOP内嵌挡住浏览器的div弹出层
首先,做一个简单的div弹出层用于测试,该弹出层的介绍可查看本博客另一篇博文:[JS新手教程]浏览器弹出div层 然后加入LODOP内嵌,LODOP可以内嵌,C-LODOP不能内嵌,可以在IE等浏览器 ...
- C# 对象哈希码
FCL的设计者认为,如果能将任何对象的任何实例放到哈希集合中,能带来很多好处.但是这里说一点,还是会存在,哈希码类似的情况,这一点大型网站架构这本书中有介绍,最好做下MD5算法.为此,System.O ...