一、Beautifu Soup库

from bs4 import BeautifulSoup
soup = BeautifulSoup(demo,"html.parser")

Tag、Name、Attributes、NavigableString、Comment

.contents 子节点的列表,将<tag>所有儿子节点存入列表

.children 子节点的迭代类型

.descendants 子孙节点的迭代类型

.parent 节点的父亲标签

.parents 节点先辈标签的迭代类型

.next_sibling(s) 返回安照HTML文本顺序的下一个平行节点标签

.previous_sibling(s) 上一个

>>> import requests
>>> r = requests.get("http://python123.io/ws/demo.html")
>>> demo = r.text
>>> demo
'<html><head><title>This is a python demo page</title></head>\r\n<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b></p>\r\n<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>\r\n</body></html>'
>>>from bs4 import BeautifulSoup

>>> soup = BeautifulSoup(demo,"html.parser")
>>> soup.prettify()
'<html>\n <head>\n <title>\n This is a python demo page\n </title>\n </head>\n <body>\n <p class="title">\n <b>\n The demo python introduces several python courses.\n </b>\n </p>\n <p class="course">\n Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\n <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">\n Basic Python\n </a>\n and\n <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">\n Advanced Python\n </a>\n .\n </p>\n </body>\n</html>'
>>> print(soup.prettify())
<html>
<head>
<title>
This is a python demo page
</title>
</head>
<body>
<p class="title">
<b>
The demo python introduces several python courses.
</b>
</p>
<p class="course">
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
Basic Python
</a>
and
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
Advanced Python
</a>
.
</p>
</body>
</html>

二、信息组织与提取

1.信息标记的三种形式:

XML:尖括号

JSON:有类型键值对

YAML:无类型

3.信息提取的一般方法

(1)完整解析信息地标记形式,再提取关键信息

(2)无视标记形式,直接搜索关键信息

(3)融合方法

实例:

>>>  import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
demo SyntaxError: unexpected indent
>>> import requests
>>> r = requests.get("http://python123.io/ws/demo.html")
>>> demo = r.text
>>> demo
'<html><head><title>This is a python demo page</title></head>\r\n<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b></p>\r\n<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>\r\n</body></html>'
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(demo,"html,parser")
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
soup = BeautifulSoup(demo,"html,parser")
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python37-32\lib\site-packages\bs4\__init__.py", line 196, in __init__
% ",".join(features))
bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: html,parser. Do you need to install a parser library?
>>> yes
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
yes
NameError: name 'yes' is not defined
>>> soup = BeautifulSoup(demo,"html.parser")
>>> from link in soup.find_all('a')
SyntaxError: invalid syntax
>>> for link in soup.find_all('a')
SyntaxError: invalid syntax
>>> for link in soup.find_all('a'):
print(link.get('href')) http://www.icourse163.org/course/BIT-268001
http://www.icourse163.org/course/BIT-1001870001

4.基于bs4库的HTML内容查找方法

<>.find_all(name,attrs,recursive,string,**kwargs)

返回一个列表类型,存储查找的结果

name:对标签名称的检索字符串

>>> soup.find_all('a')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all(['a','b'])
[<b>The demo python introduces several python courses.</b>, <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> for tag in soup.find_all(True):
print(tag.name) html
head
title
body
p
b
p
a
a
>>> import re
>>> for tag in soup.find_all(re.compile('b')):
print(tag.name) body
b

attrs:对标签属性值的检索字符串,可标注属性检索

>>> soup.find_all('p','course')
[<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses: <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>]
>>> soup.find_all(id='link1')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>]
>>> soup.find_all(id=re.compile('link'))
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]

recursive:是否对子孙全部检索,默认True

>>> soup.find_all('a',recursive=False)
[]

string:<>...</>中字符串区域的检索字符串

>>> soup.find_all(string = 'Basic Python')
['Basic Python']
>>> soup.find_all(string = re.compile("python"))
['This is a python demo page', 'The demo python introduces several python courses.']

>>> soup(string = 'Basic Python')
['Basic Python']

扩展方法:

<>.find() find_parents parent next_sibling(s) previous_sibling(s)

三、中国大学排名定向爬虫

技术路线:requests+bs4

可行性:robots协议

步骤1:获取内容 getHTMLText()

2:数据结构 fillUnivList()

3:利用DS printUnivList()

import requests
from bs4 import BeautifulSoup
import bs4 def getHTMLText(url):
try:
r = requests.get(url,timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "" def fillUnivList(ulist,html):
soup = BeautifulSoup(html,'html.parser')
for tr in soup.find('tbody').children:
if isinstance(tr,bs4.element.Tag):#过滤
tds = tr('td')
ulist.append([tds[0].string,tds[1].string,tds[3].string]) def printUnivList(ulist,num):
#tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print("{:^10}\t{:^6}\t{:^10}".format("排名","学校名称","总分"))
for i in range(num):
u = ulist[i]
print("{:^10}\t{:^6}\t{:^10}".format(u[0],u[1],u[2])) def main():
uinfo = []
url='http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html'
html = getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,20)
main()

优化后:

import requests
from bs4 import BeautifulSoup
import bs4 def getHTMLText(url):
try:
r = requests.get(url,timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "" def fillUnivList(ulist,html):
soup = BeautifulSoup(html,'html.parser')
for tr in soup.find('tbody').children:
if isinstance(tr,bs4.element.Tag):#过滤
tds = tr('td')
ulist.append([tds[0].string,tds[1].string,tds[3].string]) def printUnivList(ulist,num):
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print(tplt.format("排名","学校名称","总分",chr(12288)))
for i in range(num):
u = ulist[i]
print(tplt.format(u[0],u[1],u[2],chr(12288))) def main():
uinfo = []
url='http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html'
html = getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,20)
main()

The website is API(2)的更多相关文章

  1. The website is API(3)

    网络爬虫实战知识准备: Requests库.robots(网络爬虫排除标准).BeautifulSoup库 一.Re正则表达式 1. 简洁地表达一组字符串 通用的字符串表达框架 字符串匹配 编译: 2 ...

  2. The website is API(1)

    Requests 自动爬取HTML页面 自动网路请求提交 robots 网络爬虫排除标准 Beautiful Soup 解析HTML页面 实战 Re 正则表达式详解提取页面关键信息 Scrapy*框架 ...

  3. The website is API(4)

    1.淘宝商品信息定向爬虫 目标:获取淘宝搜索页面信息,提取其中的商品名称和价格 理解:淘宝的搜索接口 翻页的处理 技术路线:requests+re https://s.taobao.com/searc ...

  4. 我这么玩Web Api(二):数据验证,全局数据验证与单元测试

    目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试   一.模型状态 - ModelState 我理解 ...

  5. [Android]使用Dagger 2依赖注入 - API(翻译)

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5092525.html 使用Dagger 2依赖注入 - API ...

  6. [转]ASP.NET Web API(三):安全验证之使用摘要认证(digest authentication)

    本文转自:http://www.cnblogs.com/parry/p/ASPNET_MVC_Web_API_digest_authentication.html 在前一篇文章中,主要讨论了使用HTT ...

  7. ASP.NET Web API(三):安全验证之使用摘要认证(digest authentication)

    在前一篇文章中,主要讨论了使用HTTP基本认证的方法,因为HTTP基本认证的方式决定了它在安全性方面存在很大的问题,所以接下来看看另一种验证的方式:digest authentication,即摘要认 ...

  8. ASP.NET Web API(二):安全验证之使用HTTP基本认证

    在前一篇文章ASP.NET Web API(一):使用初探,GET和POST数据中,我们初步接触了微软的REST API: Web API. 我们在接触了Web API的后就立马发现了有安全验证的需求 ...

  9. 微信公众平台Js API(WeixinApi)

    微信公众平台Js API(WeixinApi): https://github.com/zxlie/WeixinApi#user-content-3%E9%9A%90%E8%97%8F%E5%BA%9 ...

随机推荐

  1. Oracle 中多个字段显示成一列

    SELECT COALESCE(A,B,C,'NA') FROM XXXXX --判断A若为空则取B,B为空这取C,C为空则取默认值'NA'

  2. 干货|浅谈iOS端短视频SDK技术实现

    短视频SDK主要包含"视频录制"和"视频编辑"这两个核心功能. 视频录制包括:视频采集.美颜.滤镜.摄像头切换.视音频采集参数设置等功能: 视频编辑包括:视频导 ...

  3. java笔记01

    java对象数组 Student[] Students = new Student[3]; 与普通数组无差 java集合类 集合类: 面向对象对事物的描述是通过对象来体现的. 为了方便对多个对象进行操 ...

  4. 吴裕雄--天生自然JAVA SPRING框架开发学习笔记:Spring基于Annotation装配Bean

    在 Spring 中,尽管使用 XML 配置文件可以实现 Bean 的装配工作,但如果应用中 Bean 的数量较多,会导致 XML 配置文件过于臃肿,从而给维护和升级带来一定的困难. Java 从 J ...

  5. Linux 目录变化监听 - python代码实现

    在python中 文件监控主要有两个库, 一个是pyinotify ( https://github.com/seb-m/pyinotify/wiki ),pyinotify依赖于Linux平台的in ...

  6. 强制浏览器以IE8版本运行

    做为一个开发人员,经常被要求前端页面兼容ie8及以上,所以有时候我们希望ie默认以ie8的版本打开我们的页面. 1.“文档模式”: 在html页面中加入类似下面的代码: <meta http-e ...

  7. NRF24L01中断双向传输数据

    NRF24L01是一款比较常见的无线通讯芯片,不过有个缺点就是只能半双工通讯,当涉及到双向通讯时就比较麻烦一些·,特别是想要做无线IAP数据需要一直来回发送,这点无疑然人恶心到想吐,不过还好有数据中断 ...

  8. 浅入深出Java输入输出流主线知识梳理

      Java把不同类型的输入.输出,这些输入输出有些是在屏幕上.有些是在电脑文件上, 都抽象为流(Stream) 按流的方向,分为输入流与输出流,注意这里的输出输出是相对于程序而言的,如:如对于一个J ...

  9. .NET CORE 热更新,否则提示DLL文件在使用中

    1.创建空目录,取名updatesite,里面放置app_ffline.htm文件,网站更新中访问使用,内容随意 2.updatesite目录下面创建Release目录,用于放置更新的dll文件 3. ...

  10. 吴裕雄--天生自然MySQL学习笔记:MySQL 数据类型

    MySQL中定义数据字段的类型对你数据库的优化是非常重要的. MySQL支持多种类型,大致可以分为三类:数值.日期/时间和字符串(字符)类型. 数值类型 MySQL支持所有标准SQL数值数据类型. 这 ...