python3 网络数据采集1

第一部分:

一、可靠的网络连接:

使用库:

python标准库: urllib

python第三方库:BeautifulSoup

安装:pip3 install  beautifulsoup4

导入:import  bs4

 cat scrapetest2.py
#!/usr/local/bin/python3 from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.error import HTTPError def getTitle(url):
try:
html = urlopen(url)
except HTTPError as e:
return None
try:
bsObj = BeautifulSoup(html.read())
title = bsObj.body.h1
except AttributeError as e:
return None
return title x = 'http://pythonscraping.com/pages/page1.html'
title = getTitle(x) if title == None:
print('Title could not be found.')
else:
print(title) #######执行结果#######
python3 scrapetest2.py
/usr/local/lib/python3.5/site-packages/bs4/__init__.py:181: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. The code that caused this warning is on line 21 of the file scrapetest2.py. To get rid of this warning, change code that looks like this: BeautifulSoup(YOUR_MARKUP}) to this: BeautifulSoup(YOUR_MARKUP, "html.parser") markup_type=markup_type))
<h1>An Interesting Title</h1>

二、 复杂的HTML解析

.get_text()   会把正在处理的HTML文档中所有的标签(超链接、段落、标签)都清除,然后返回一个只包含文字的字符串。

 cat bs41.py
#!/usr/local/bin/python3 from urllib.request import urlopen
from bs4 import BeautifulSoup html = urlopen('http://www.pythonscraping.com/pages/warandpeace.html')
bsObj = BeautifulSoup(html) nameList = bsObj.findAll('span',{'class':'green'})
for name in nameList:
print(name.get_text()) #################
返回所有绿色的字体
Anna
Pavlovna Scherer
Empress Marya
Fedorovna
Prince Vasili Kuragin
Anna Pavlovna
St. Petersburg
the prince
Anna Pavlovna
Anna Pavlovna
the prince
the prince
the prince
Prince Vasili
Anna Pavlovna
Anna Pavlovna
the prince
Wintzingerode
King of Prussia
le Vicomte de Mortemart
Montmorencys
Rohans
Abbe Morio
the Emperor
the prince
Prince Vasili
Dowager Empress Marya Fedorovna
the baron
Anna Pavlovna
the Empress
the Empress
Anna Pavlovna's
Her Majesty
Baron
Funke
The prince
Anna
Pavlovna
the Empress
The prince
Anatole
the prince
The prince
Anna
Pavlovna
Anna Pavlovna

BeautifulSoup 的find() 和findAll()

用途:通过标签的不同属性过滤HTML页面,查找需要的标签组或单个标签。

findAll(tag,  attributes,  recursive, text, limit,  keywords)

findAll = find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)

find(tag, attributes, recursive, text, keywords)

find(self, name=None, attrs={}, recursive=True, text=None, **kwargs)

说明: tag  可以传一个标签的名称或多个标签名称组成的python列表做标签参数;findAll({'h1', 'h2', 'h3', 'h4', 'h5', 'h6',})

attributes  用字典封装一个标签的若干属性和对应的属性值; .findAll("span", {"class":{"green", "red"}})

recursive   递归参数是一个布尔变量,默认值True;如果是True会查找变迁参数的所有子标签,以及子标签的子标签;如果设置为False,就只查找文档的一级标签;

text     文本参数 ,它是用标签的文本内容去匹配,而不是标签的属性;nameList = bsObj.findAll(text='the prince')    print(len(nameList))    结果是:7

limit    范围限制参数x,按照网页上的顺序排序获取前面的x项;

keywords   关键词参数,选择具有指定属性的标签;

关键词参数:
allText = bsObj.findAll(id='text')
print(allText[0].get_text())
######
下面两行代码一样:
bsObj.findAll(id='text')
bsObj.findAll("", {"id" : "text"})
######
在class后面加一个下划线
bsObj.findAll(class_='green')
也可以用属性参数把class用引号包起来
bsObj.findAll("", {"class":"green"})

BeautifulSoup库里的两种对象:

1,BeautifulSoup 对象

2,标签Tag对象

直接调用子标签获取的一列对象或单个对象; bsObj.div.h1

另外两个如下:

3, NavigableString对象

用来表示标签里的文字,不是标签;

4,Comment  对象

用来查找 HTML文档的注释标签 <!--像这样-->

导航树:

通过标签在文档中的位置来查找标签, 导航树Navigating Trees作用;

1,处理子标签和其他后代标签;

子标签就是一个父标签的下一级;而后代标签是指一个父标签下面所有级别的标签;

查找子标签,可以用 .children标签;

########子标签#######
# cat beau.py
#!/usr/local/bin/python3 from urllib.request import urlopen
from bs4 import BeautifulSoup html = urlopen('http://www.pythonscraping.com/pages/page3.html')
bsObj = BeautifulSoup(html) for child in bsObj.find("table",{'id':'giftList'}).children:
print(child)
########################## cat beau.py
#!/usr/local/bin/python3 from urllib.request import urlopen
from bs4 import BeautifulSoup html = urlopen('http://www.pythonscraping.com/pages/page3.html')
bsObj = BeautifulSoup(html) for child in bsObj.find("table",{'id':'giftList'}).descendants:
print(child)

2,处理兄弟标签;

python 网络数据采集1的更多相关文章

  1. 笔记之Python网络数据采集

    笔记之Python网络数据采集 非原创即采集 一念清净, 烈焰成池, 一念觉醒, 方登彼岸 网络数据采集, 无非就是写一个自动化程序向网络服务器请求数据, 再对数据进行解析, 提取需要的信息 通常, ...

  2. Python网络数据采集7-单元测试与Selenium自动化测试

    Python网络数据采集7-单元测试与Selenium自动化测试 单元测试 Python中使用内置库unittest可完成单元测试.只要继承unittest.TestCase类,就可以实现下面的功能. ...

  3. Python网络数据采集6-隐含输入字段

    Python网络数据采集6-隐含输入字段 selenium的get_cookies可以轻松获取所有cookie. from pprint import pprint from selenium imp ...

  4. Python网络数据采集4-POST提交与Cookie的处理

    Python网络数据采集4-POST提交与Cookie的处理 POST提交 之前访问页面都是用的get提交方式,有些网页需要登录才能访问,此时需要提交参数.虽然在一些网页,get方式也能提交参.比如h ...

  5. Python网络数据采集3-数据存到CSV以及MySql

    Python网络数据采集3-数据存到CSV以及MySql 先热热身,下载某个页面的所有图片. import requests from bs4 import BeautifulSoup headers ...

  6. Python网络数据采集2-wikipedia

    Python网络数据采集2-wikipedia 随机链接跳转 获取维基百科的词条超链接,并随机跳转.可能侧边栏和低栏会有其他链接.这不是我们想要的,所以定位到正文.正文在id为bodyContent的 ...

  7. Python网络数据采集1-Beautifulsoup的使用

    Python网络数据采集1-Beautifulsoup的使用 来自此书: [美]Ryan Mitchell <Python网络数据采集>,例子是照搬的,觉得跟着敲一遍还是有作用的,所以记录 ...

  8. Python网络数据采集PDF

    Python网络数据采集(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/16c4GjoAL_uKzdGPjG47S4Q 提取码:febb 复制这段内容后打开百度网盘手 ...

  9. python网络数据采集的代码

    python网络数据采集的代码 https://github.com/REMitchell/python-scraping

  10. [python] 网络数据采集 操作清单 BeautifulSoup、Selenium、Tesseract、CSV等

    Python网络数据采集操作清单 BeautifulSoup.Selenium.Tesseract.CSV等 Python网络数据采集操作清单 BeautifulSoup.Selenium.Tesse ...

随机推荐

  1. python, 在信用评级中,计算KS statistic值

    # -*- coding: utf-8 -*- import pandas as pd from sklearn.grid_search import GridSearchCV from sklear ...

  2. ActiveMQ 事务和XA

    1. 客户端怎样显式地使用事务? producer 开启事务(代码片段): ActiveMQSession session = (ActiveMQSession)connection.createSe ...

  3. Qt Widgets——动作类与小部件菜单项

    本文主要涉及以下三个类: QAction ——QWidgetAction QActionGroup QAction可称为动作类,它一般可当作菜单中的项组成菜单,也可作为工具栏上的按钮,它主要由图标.文 ...

  4. Talend 从Excel导入Saleforce数据(二) TMAP是精髓

    TMap LookUp 经过测试的结果: ------------------------------------------ LookUp最好从CSV读数据,这样是最快了(20万记录1s).从Sal ...

  5. vs 编译库文件 Qt编译库文件

    QT 库能不能用 需要关注是minGW 还是MSVC编译的 Qt MinGW与MSVC对比  转:https://blog.csdn.net/u013185164/article/details/48 ...

  6. 命令创建Vue

    创建vue+webpack vue init webpack projectName 基础 Vue+webpack+Vux 新建文件命令 # install vue-cli npm install - ...

  7. Oracle中使用PL/SQL如何定义参数、参数赋值、输出参数和 if 判断

    1.pl/sql如何定义参数 declare --1)定义参数 -- ban_Id number; ban_Name ); 2.pl/sql如何参数赋值 --2)参数赋值-- ban_Id :; ba ...

  8. shell脚本分析一

    Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁.Shell 既是一种命令语言,又是一种程序设计语言.Shell 是指一种应用程序,这个应用程序提供了一个界面,用户通过这个界 ...

  9. day9-复习学习python实例

    学习实例代码 #求1到100的和print ("##################1到100求和#################")def sum(a,b): s = 0 fo ...

  10. linux:centOs7没有eth0网卡

    1.修改ifcfg-ens33为ifcfg-eth0 cd /etc/sysconfig/network-scripts/ su root                 #进入root模式,需要输入 ...