python使用BeautifulSoup分析网页信息的方法

yipeiwu_com6年前Python基础

本文实例讲述了python使用BeautifulSoup分析网页信息的方法。分享给大家供大家参考。具体如下:

这段python代码查找网页上的所有链接,分析所有的span标签,并查找class包含titletext的span的内容

复制代码 代码如下:
#import the library used to query a website
import urllib2

#specify the url you want to query
url = "http://www.python.org"

#Query the website and return the html to the variable 'page'
page = urllib2.urlopen(url)

#import the Beautiful soup functions to parse the data returned from the website
from BeautifulSoup import BeautifulSoup

#Parse the html in the 'page' variable, and store it in Beautiful Soup format
soup = BeautifulSoup(page)

#to print the soup.head is the head tag and soup.head.title is the title tag
print soup.head
print soup.head.title

#to print the length of the page, use the len function
print len(page)

#create a new variable to store the data you want to find.
tags = soup.findAll('a')

#to print all the links
print tags

#to get all titles and print the contents of each title
titles = soup.findAll('span', attrs = { 'class' : 'titletext' })
for title in allTitles:
print title.contents

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python中实现的RC4算法

闲暇之时,用Python实现了一下RC4算法 编码 UTF-8 class 方式 #/usr/bin/python #coding=utf-8 import sys,os,hash...

python 调用有道api接口的方法

python 调用有道api接口的方法

初学python ,研究了几天,写了一个python 调用 有道api接口程序 效果看下图: 申明:代码仅供和我一样的初学者学习交流 有道api申请地址http://fanyi.you...

Python实现快速计算词频功能示例

本文实例讲述了Python实现快速计算词频功能。分享给大家供大家参考,具体如下: 这几天看到一位同事的代码,方法如下: def cut_word(body): temp_dict...

Python实现的合并两个有序数组算法示例

本文实例讲述了Python实现的合并两个有序数组算法。分享给大家供大家参考,具体如下: 思路 按位循环比较两个数组,较小元素的放入新数组,下标加一(注意,较大元素对应的下标不加一),直到...

详谈python在windows中的文件路径问题

在使用python通过open()函数来打开文件的时候,传递绝对路径给open()的时候,发现路径参数的内容与想象中的有所出入: 由于windows的路径分隔符使用的是反斜杠\,它刚刚好...