一个小爬虫学到的

突然要听报告 写个小爬虫爬爬报告实时通知更新状况

复(yu)习(xi)BeautifulSoup知识

#!/usr/bin/python
#-*-encoding=utf8-*-
from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
</body>
"""
print type(html)
soup = BeautifulSoup(html, 'lxml')
#使用tag查找
#print soup.p #只能选择第一个tag下的内容
#print soup.p.string #得到内部的内容

#遍历文档树dom .contents
#print len(soup.contents) # 返回html所有元素的list
#print type(soup.contents) #type list
#print soup.contents[0].content #None
#print type(soup.contents[0].content) #NoneType
#print soup.body.p.contents[0]

#.children 返回listiterator
#遍历方法
#for child in soup.children:
#	print child

#find_all
#find 返回的是只包含一个元素的list
#print soup.find_all('p', limit=1) #返回list 限定一个

#---------下述方法为css选择期器soup.select() 返回list------
#通过类名查找
#print 'class= "title"', soup.select( '.title' )
#print 'id= "link1"', soup.select('#link1')

#组合查找(标签名, 类名, id名), 使用空格分开
#print soup.select('p #link1')

#子标签查找
ele =  soup.select('body > p:nth-of-type(1)') #size : n
for i in ele:
	print i.get_text().encode('utf8')

#属性查找	
#print soup.select('a[class="sister"]')

#也可以组合查找
#print soup.select('p a[class="sister"]')

#最后关于list中元素的获取 使用get_text()
#data = type(soup.select( 'a[href="http://example.com/tillie"]' )[0].get_text())
#`print data
s = '@jin'
if '@'==s[0]:
	print "@==s[0]"

伪装自己

header = {
		'User-Agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0",
		'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
		'Accept-Language': "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
		'Accept-Encoding': "gzip, deflate",
		'Connecting': "keep-alive"
	}
	timeout = random.choice(range(100, 120))
	content = requests.get(url, headers=header, timeout=timeout).content

解析html

def analyse_html(html):
	soup = BeautifulSoup(html, 'lxml');
	data = soup.select('.NewsBody > p') # path: according to firfox	
	return data # change nth-child to nth-of-type(3)
	# type(data)=unicode

sublime不支持中文,蹩脚英文请见谅
需要注意的是, 解析路径时要使用默认浏览器, 我的是firfox

  • 写入数据

def write_data(info):
	os.chdir("/home/jin/python/") # pwd
	file = open("data.txt", 'w') # no 'rw'
	file.truncate() # flip file
	for ele in info:
		trueEle = ele.get_text().encode('utf8').lstrip();
		if len(trueEle) and ord(trueEle[0]) >= ord('1') and ord(trueEle[0]) <= ord('9'):
			file.write(ele.get_text().encode('utf8')) #type(ele.encode('utf8'))='str'
			file.write('\n')
	file.close()

这时候特别要注意编码问题,不清楚会踩到很多坑
菜鸟一枚,错误欢迎指正
附上实时结果

27、(11月10日 周五)Charged systems in variable dielectric media
26、(11月17日 周五)肖益民教授题为“Recent Developments in Theory of Random Fields”的报告
25、(11月10日 周五)Towards an explicit description of local theta correspondence over p-adic fields
24、(11月7日 周二)On Vertex Operator Algebras
23、(11月4日 周六)Concordance Measure-based Feature Screening and Variable Selection
22、(11月3日 周五)南京邮电大学王海金教授的学术报告
21、(11月3日 周五)南京大学张强教授的学术报告 
20、(11月1日 周三)Optimal Mixture Designs for Complex System
19、(11月10日 周五)“Deep Revolution” in Image Restoration and Beyond 图像恢复与超越中的“深刻革命”
18、(11月2日 周四) 概率统计学术报告 Flexible sequential or sliced designs for computer emulations
17、(11月3日 周五) 浙江大学数学科学学院高等数学所 系列学术报告 201711
16、(11月1日 周三) Finite Morse Index Solutions of the Allen-Cahn Equation
15、(11月1日 周三 和 11月3日 周五) Dilogarithm identities and cluster algebras
14、(11月3日 周五)Nguyen教授题为“On some generalized polyhedral convex constructions”的报告
13、(10月26日 周四)Super-Resolution Ultrasound Imaging and 3D Breast Ultrasound Tomography
12、(10月31日 周二)LPRE criterion based estimating equation approaches for the error-in-covariables multiplicative regression models
11、(10月26日 周四)New Developments on Convergence and Collasping Theorems in Riemannian Geometry
10、(10月27日 周五) Some rigidity results on pseudoharmonic maps from pseudo-Hermitian manifolds
9、(10月26日 周四)基于最小路径的血管及胆道图像分割研究与应用
8、(10月19日 周四)On the Rigidity of Riemannian-Penrose Inequality for Asymptotically Flat 3-manifolds with Corners
7、(10月26日周四) Solvability of the 2-D Stokes Immersed Boundary Problem
6、(10月23日 周一)Sharp $L^p$--$L^q$ estimate for the spherical harmonic projection
5、(10月16日 周一)白中治研究员题为“Preconditioning and Iterative Methods for Under- and Over-determined Linear Systems”的报告 
4、(10月19日 周四)张纪峰研究员题为《集值输出系统的辨识与控制》的报告
3、(10月12日 周四)统计学术讲座Scalable and efficient statistical inference in Cox regression model using the MapReduce paradigm
2、(10月12日 周四)On The Negativity of Ricci Curvatures of Complete Conformal Metrics
1、(10月23日 周一)Ramanujan优美图 ----- 数论与图论的结合
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值