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中实现参数类型检查的简单方法

Python是一门弱类型语言,很多从C/C++转过来的朋友起初不是很适应。比如,在声明一个函数时,不能指定参数的类型。用C做类比,那就是所有参数都是void*类型!void类型强制转换在...

了解不常见但是实用的Python技巧

了解不常见但是实用的Python技巧

1.交换变量值 2.将一列表中的所有元素拼接成字符串 3.查找list中最高频率的值 4.检查两个单词是否是字谜(组成的字母和对应数量一致) 5.反转字符串 6.反转列表 7...

Python系统监控模块psutil功能与经典用法分析

本文实例讲述了Python系统监控模块psutil功能与经典用法。分享给大家供大家参考,具体如下: 1.  psutil模块概述 psutil是一个跨平台库(http://co...

Python使用剪切板的方法

此段代码可以利用剪切板,完成自动复制粘贴等功能。(Windows)  import sys import os.path import win32clipboard as...

python3.6 +tkinter GUI编程 实现界面化的文本处理工具(推荐)

python3.6 +tkinter GUI编程 实现界面化的文本处理工具(推荐)

更新: 2017.07.17  补充滚动条、win批处理拉起py 2017.08.13  新增自定义图标 一、背景: 1.工作中自己及同事在查数据库、测试接口时需要对一些字符串或json...