python 页面信息抓取

1. 特点

  在python 解析html这篇文章中已经做了初步的介绍,接下来再坐进一步的说明。python抓取页面信息有下面两个特点:
  

  • 依赖于HTML的架构。

  • 微小的变化可能会导致抓取失败,这取决于你编码的技巧。


2. 抓取演示样例

  首先看一下百度视频网页的源码,大致浏览下,选定要抓取的网页元素。


  src
  
  如果我们要对div标签id为focusCarouselList里的相关内容进行提取。

首先进入python命令行环境,先依照下面代码打开网页并读取内容。
  

>>>
>>> import urllib
>>> from bs4 import BeautifulSoup
>>>
>>> httpRespone = urllib.urlopen(“http://video.baidu.com“)
>>>
>>> httpRespone.code
200
>>>

  将页面信息读入到html的一个变量中:html = httpRespone.read()
  使用BeautifulSoup解析这个页面:bs = BeautifulSoup(html,"lxml")


  查找id为ocusCarouselList的div标签:focusList = bs.find('div',id='focusCarouselList')
  
  bs
  
  在focusList中查找这一div中全部的超链接:allLinks = focusList.find_all('a')
  可用allLinks[0]直接訪问第一个链接的内容:
  link0
  
  如果要在这些超链接中查找标题为“协警押送嫌犯遭其同伙突击”,可用下面代码:
  videoLink1 = bs.find('a',{'title':'协警押送嫌犯遭其同伙突击'})
  title
  
  videoLink1[‘href’]能够直接获取到链接的地址。


  
  查找全部图片的标签:imgLinks = focusList.find_all('img')
  获取某个图片链接的源地址:imgLinks[0]['src']
  img

posted @ 2017-07-31 14:47  yfceshi  阅读(406)  评论(0编辑  收藏  举报