python爬虫入门——初步采集
来源:互联网 发布:c语言共用体union例子 编辑:程序博客网 时间:2024/06/05 17:44
#获取维基百科网站的任何页面并提取页面链接 import urllib2import bs4html = urllib2.urlopen("http://en.wikipedia.org/wiki/Kevin_Bacon")bsObj = bs4.BeautifulSoup(html.read(), "lxml")for link in bsObj.find("a"): if 'href' in link.attrs: print(link.attrs['href'])
以上代码问题:存在不需要的链接,如侧边栏、页眉、页脚的各种链接。
所需要链接的特点:
它们都在id是bodyContent的div标签里
URL 链接不包含分号
URL 链接都以 /wiki/ 开头
import urllib2import bs4import rehtml = urllib2.urlopen("http://en.wikipedia.org/wiki/Kevin_Bacon")bsObj = bs4.BeautifulSoup(html.read(), "lxml")#利用正则表达式筛选出了不必要的链接for link in bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$")): if 'href' in link.attrs: print(link.attrs['href'])
继续改进:
一个函数getLinks,可以用维基百科词条/wiki/<词条名称>形式的URL链接作为参数,然后以同样的形式返回一个列表,里面包含所有的词条 URL 链接。
一个主函数,以某个起始词条为参数调用getLinks,再从返回的URL列表里随机选择一个词条链接,再调用 getLinks,直到我们主动停止,或者在新的页面上没有词条链接了,程序才停止运行。
import urllib2import bs4import reimport datetimeimport randomrandom.seed(datetime.datetime.now())def getLinks(articleUrl): html = urllib2.urlopen("http://en.wikipedia.org"+articleUrl) bsObj = bs4.BeautifulSoup(html.read(), "lxml") return bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/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)
0 0
- python爬虫入门——初步采集
- python爬虫案例——csdn数据采集
- python爬虫案例——糗事百科数据采集
- python爬虫案例——百度贴吧数据采集
- python爬虫案例——东方财富股票数据采集
- python爬虫案例——新浪腾讯股票数据采集
- Python 爬虫入门(二) HTTP协议初步
- Python爬虫入门——爬取贴吧图片
- Python爬虫入门——正则表达式
- Python基础知识——爬虫入门
- python网络爬虫初步
- Python爬虫初步
- Python爬虫初步
- Python爬虫初步
- 初步尝试python爬虫
- python实现简易采集爬虫
- python实现简易采集爬虫
- Python爬虫小说采集程序
- elasticsearch学习笔记(一)
- apache和tomcat有什么不同
- 关于申请微信公众号(服务号)的材料和流程
- S2 第一本书myschool 第二章上机1-7
- c#调用delphi写的dll遇到并解决的问题
- python爬虫入门——初步采集
- S2第二章课后
- [APP接口] -- PHP开发APP接口(二)
- Elsa项目成长日记
- Unity破解失败pattern not found解决办法
- 自动识别文字编码并且转换为目标编码(php 正则)
- accp7.0-s2 优化MySchool数据库
- 记录一些网络编程要点
- mybatis配置通用dao和service时出现org.springframework.beans.factory.BeanCreationException异常