Python网络数据采集笔记_第1页
Python网络数据采集笔记_第2页
Python网络数据采集笔记_第3页
Python网络数据采集笔记_第4页
Python网络数据采集笔记_第5页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、1. BeautifulSoup简介from urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen()#打开一个网址bsObj = BeautifulSoup(html.read(),html.parser)#建立了一个美丽汤对象,以网页内容为参数#调用html.read获取网页的HTML内容#这样就可以把HTML内容传到美丽汤对象print (bsObj.h1) #提取h1标签导入urlopen,然后调用html.read()获取网页的HTML内容,这样就可以把H

2、TML内容传到BeautifulSoup对象用bsObj.h1从对象里提取h1标签任何HTML文件的任意节点的信息都可以被提取出来处理异常html = urlopen(/pages/page1.html)这一句可能出现两种异常:l 网页在服务器上不存在(提取网页时出现错误)返回HTTP错误,urlopen函数抛出HTTPError异常处理:try: html = urlopen(/pages/page1.html) except HTTPError as e: print(e)#返回

3、空值,中断程序,或者执行另一个方案 else: #程序继续l 服务器不存在(连接打不开、写错了),urlopen就会返回一个None对象,可以增加一个判断语句检测返回的html是不是None:if html is None:print(URL is not found)else: #程序继续 第一个爬虫:from urllib.request import urlopenfrom urllib.error import HTTPError,URLErrorfrom bs4 import BeautifulSoupdef getTitle(url): try: html = urlopen(ur

4、l) except (HTTPError,URLError) as e: return None try: bsObj = BeautifulSoup(html.read(),html.parser) title = bsObj.html.head.title except AttributeError as e: return None return titletitle = getTitle(/#signin)if title = None: print(title could not be found)else: print(title)2. 复杂

5、HTML解析/pages/warandpeace.html抓出整个页面,然后创建一个BeautifulSoup对象:from urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen(/pages/warandpeace.html)bsObj = BeautifulSoup(html)通过BeautifulSoup对象,可以用findAll函数抽取只包含在某个标签里的文字,如:namelist =

6、 bsObj.findAll(span,class:green)for name in namelist: print(name.get_text() #得到一个包含人物名称的Python列表find()与findAll()函数findAll(tag,attributes,recursive,text,limit,keywords)find(tag, attributes,recursive,text,keywords)tag传一个或多个标签的名称组成的列表做标签函数,例如:.findAll(h1,h2,h3,h4,h5)attributes用一个Python字典封装一个标签的若干属性和对应的

7、属性值,例如:.findAll(span,class:green,red #返回红色与绿色的span标签text用标签的文本内容去匹配,例如:namelist = bsObj.findAll(text = the prince)print(len(namelist)其他BeautifulSoup对象BeautifulSoup对象标签tag对象NavigableString对象Comment对象导航树1.处理子标签和其他后代标签children()函数和descendants()函数如果只想找出子标签,可以用.children标签from urllib.request import urlope

8、nfrom bs4 import BeautifulSouphtml = urlopen(/pages/warandpeace.html)bsObj = BeautifulSoup(html)for child in bsObj.find(table,id:giftlist).children: print(child) 2.处理兄弟标签next_siblings()函数可以让手机表格数据成为简单的事情for sibling in bsObj.find(table,id:giftlist).tr.next_siblings:print(s

9、ibling)#这段代码会打印产品列表里所有行的产品(表格标题除外,自己不能是自己的兄弟)3.父标签处理parent和parents正则表达式和BeautifulSoup获取属性对于一个标签对象,可以用下面的代码获取它的全部属性:myTag.attrs要注意这行代码返回的是一个Python对象,可以获取和操作这些属性,例如要获取图片的资源位置src,可以使用:myImgTag.attrssrcLambda表达式例如:soup.findAll(lambda tag: len(tag.attrs) = 2)3. 开始采集遍历单个域名获取维基百科网站的任何页面并提取页面链接的Python代码:fro

10、m urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen()bsObj = BeautifulSoup(html)for link in bsObj.findAll(a):if href in link.attrs:print(link.attrshref)会包含一些不需要的链接,例如侧边栏页面页脚链接指向词条页面的链接的共同点:它们都在id是bodyContent的div标签里,URL链接不含冒号,URL链接可能都有共同的开头,。因此可以改成for link

11、in bsObj.find(div,id:bodyContent).findAll(a,href=pile(/wiki/)(?!:).)*$)from urllib.request import urlopen from bs4 import BeautifulSoup import datetimeimport randomimport rerandom.seed(datetime.datetime.now()def getLinks(articleUrl):html = urlopen(+articleUrl)bsObj = Beau

12、tifulSoup(html)return bsObj.find(div,id:bodyContent).findAll(a,href = pile(/wiki/)(?!:).)*$)links = getLinks(/wiki/Kevin_Bacon)while len(links) 0:newArticle = linksrandom.randint(0,len(links)-1).attrshrefprint(newArticle)links = getLinks(newArticle)采集整个网站from urllib.request import urlopen from

13、 bs4 import BeautifulSoup import repages = set()def getLinks(pageUrl):global pageshtml = urlopen(+pageUrl)bsObj = BeautifulSoup(html)for link in bsObj.findAll(a,href = pile(/wiki/):if href in link.attrs:if link.attrshref not in pages:#我们遇到了新的页面newPage = link.attrshrefprin

14、t(newPage)pages.add(newPage)getLinks(newPage)getLinks()一开始,用getLinks处理一个空URL,其实是维基百科的主页,因为在函数里空URL就是。然后,遍历首页上每个链接,并检查是否已经在全局变量集合pages里面了(已经采集的页面集合)。如果不在,就打印到屏幕上,并把链接加入pages集合,再用getLinks递归的处理这个链接。收集整个网站数据from urllib.request import urlopen from bs4 import BeautifulSoup import rep

15、ages = set()def getLinks(pageUrl):global pageshtml = urlopen(g+pageUrl)bsObj = BeautifulSoup(html)try:print(bsObj.h1.get_text()print(bsObj.find(id=mw-content-text).findAll(p)0)print(bsObj.find(id=ca-edit).find(span).find(a).attrshef)except AttributeError:print(页面缺少一些属性,不过不用担心)for lin

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论