码迷,mamicode.com
首页 > 编程语言 > 详细

python 爬虫(一)

时间:2016-12-27 20:29:17      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:except   包含   perror   网络   pen   could not   http   用户   page   

1. 一次简单的网页访问

urllib 是一个标准的python库(意味着不需要安装任何附件的东西来运行这个demo),包含了通过网络请求数据的方法,处理cookies,甚至更改metadata比如headers和用户代理。

urlopen 这个方法用来通过网络访问远程数据,就是发送一个get请求到制定的url地址。

技术分享
1 from urllib.request import urlopen
2 html = urlopen(http://pythonscraping.com/pages/page1.html)
3 print(html.read())
View Code

2. BeautifulSoup的简单介绍

    这个模块是一个html/xml解析器,它可以很好的处理不规范标记并生成剖析树。

   I  installing BeautifulSoup  

       linux:apt-get install python-bs4  或者 pip install beautifulsoup4

   II 在这个模块(bs4)中BeautifulSoup是最常用的

技术分享
1 from urllib.request import urlopen
2 from bs4 import BeautifulSoup
3 
4 html = urlopen("http://www.pythonscraping.com/pages/page1.html")
5 bsobj = BeautifulSoup(html.read(), html.parser)
6 print(bsobj.h1)
7 
8 #输出:<h1>An Interesting Title</h1>
View Code

 3. 异常处理

   I 在服务上没有找到请求的地址 一个http error错误会被返回 这个错误可能是 404 page  not found 500 Internal server Error 这些所有的情况urlopen方法会抛出异常HTTPError

1 try:
2     html = urlopen("http://www.pythonscraping.com/exercises/exercise1.html")
3 except HTTPError as e:
4     print(e)
5      #return null,break or do some other ‘plan B‘
6 else:
7     #program continues

   II 服务没有找到,urlopen会返回None

1 if html is None:
2     print("URL is not found")
3 else:
4     #program continues

一个捕获各种异常的写法:

 1 from urllib.request import urlopen
 2 from urllib.error import HTTPError
 3 from bs4 import BeautifulSoup
 4 def getTitle(url):
 5   try:
 6     html = urlopen(url)
 7   except HTTPError as e:
 8     return None
 9   try:
10     bsObj = BeautifulSoup(html.read())
11     title = bsObj.body.h1
12   except AttributeError as e:
13     return None
14   return title
15 title = getTitle("http://www.pythonscraping.com/exercises/exercise1.html")
16 if title == None:
17   print("Title could not be found")
18 else:
19   print(title)

 

python 爬虫(一)

标签:except   包含   perror   网络   pen   could not   http   用户   page   

原文地址:http://www.cnblogs.com/someoneHan/p/6224293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!