当前位置:文档之家› Python网络数据采集笔记

Python网络数据采集笔记

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内容,这样就可以把HTML内容传到BeautifulSoup对象用bsObj.h1从对象里提取h1标签任何HTML文件的任意节点的信息都可以被提取出来处理异常html = urlopen('/pages/page1.html')这一句可能出现两种异常:网页在服务器上不存在(提取网页时出现错误)——返回HTTP错误,urlopen函数抛出HTTPError异常处理:try:html = urlopen('/pages/page1.html') except HTTPError as e:print(e)#返回空值,中断程序,或者执行另一个方案else:#程序继续服务器不存在(连接打不开、写错了),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(url)except (HTTPError,URLError) as e:return Nonetry:bsObj = BeautifulSoup(html.read(),'html.parser')title = bsObj.html.head.titleexcept AttributeError as e:return Nonereturn titletitle = getTitle('https:///#signin')if title == None:print('title could not be found')else:print(title)2.复杂HTML解析/pages/warandpeace.html抓出整个页面,然后创建一个BeautifulSoup对象:from urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen(‘/pages/warandpeace.html’)bsObj = BeautifulSoup(html)通过BeautifulSoup对象,可以用findAll函数抽取只包含在某个标签里的文字,如:namelist = 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字典封装一个标签的若干属性和对应的属性值,例如:.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 urlopenfrom 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(sibling)#这段代码会打印产品列表里所有行的产品(表格标题除外,自己不能是自己的兄弟)3.父标签处理parent和parents正则表达式和BeautifulSoup获取属性对于一个标签对象,可以用下面的代码获取它的全部属性:myTag.attrs要注意这行代码返回的是一个Python对象,可以获取和操作这些属性,例如要获取图片的资源位置src,可以使用:myImgTag.attrs[‘src’]Lambda表达式例如:soup.findAll(lambda tag: len(tag.attrs) == 2)3.开始采集遍历单个域名获取维基百科网站的任何页面并提取页面链接的Python代码:from urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen("")bsObj = BeautifulSoup(html)for link in bsObj.findAll("a"):if 'href' in link.attrs:print(link.attrs['href'])会包含一些不需要的链接,例如侧边栏页面页脚链接指向词条页面的链接的共同点:它们都在id是bodyContent的div标签里,URL链接不含冒号,URL链接可能都有共同的开头,。

因此可以改成for link in bsObj.find("div",{"id":"bodyContent"}).findAll("a",href=pile("^(/wiki/)((?!:).)*$"))from urllib.request import urlopenfrom bs4 import BeautifulSoupimport datetimeimport randomimport rerandom.seed(datetime.datetime.now())def getLinks(articleUrl):html = urlopen(""+articleUrl)bsObj = BeautifulSoup(html)return bsObj.find("div",{"id":"bodyContent"}).findAll("a",href = pile("^(/wiki/)((?!:).)*$"))links = getLinks("/wiki/Kevin_Bacon")while len(links) > 0:newArticle = links[random.randint(0,len(links)-1)].attrs["href"] print(newArticle)links = getLinks(newArticle)采集整个网站from urllib.request import urlopenfrom bs4 import BeautifulSoupimport 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.attrs['href'] not in pages:#我们遇到了新的页面newPage = link.attrs['href']print(newPage)pages.add(newPage)getLinks(newPage)getLinks("")一开始,用getLinks处理一个空URL,其实是维基百科的主页,因为在函数里空URL就是。

然后,遍历首页上每个链接,并检查是否已经在全局变量集合pages里面了(已经采集的页面集合)。

如果不在,就打印到屏幕上,并把链接加入pages集合,再用getLinks递归的处理这个链接。

收集整个网站数据from urllib.request import urlopenfrom bs4 import BeautifulSoupimport repages = 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").attrs['hef'])except AttributeError:print("页面缺少一些属性,不过不用担心")for link in bsObj.findAll("a",href=pile("^(/wiki/)")):if 'href' in link.attrs:if link.attrs['href'] not in pages:#我们遇到了新页面newPage = link.attrs['href']print("---------\n"+newPage)pages.add(newPage)getLinks(newPage)getLinks("")这个for循环和原来的采集程序基本上是一样的(除了打印一条虚线来分离不同的页面内容之外)。

相关主题