zoukankan      html  css  js  c++  java
  • python 爬虫(一)

    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)
  • 相关阅读:
    Asp.net 文件下载,中文文件名出现乱码
    存储过程中执行动态Sql语句
    SQLServer : EXEC和sp_executesql的区别
    C# 从服务器下载文件代码
    在windows 7 上为 sqlserver 2008 启用远程访问
    数字求和
    大道至简第一章读后感
    作业
    SharePoint2013 App 开发中 自定义网站栏,内容类型,列表。
    SharePoint2013 App开发模式
  • 原文地址:https://www.cnblogs.com/someoneHan/p/6224293.html
Copyright © 2011-2022 走看看