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

yipeiwu_com5年前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在提示符下使用open打开文件失败的原因及解决方法

浅谈python在提示符下使用open打开文件失败的原因及解决方法

题目:在提示符下使用open打开一个文件 刚开始网上看了下打开的方式,结果一直实现不了,报错是没找到这个文件,而且和我输入的文件名不一样。 错误如下: >>>ope...

Scrapy框架使用的基本知识

scrapy是一个基于Twisted的异步处理框架,可扩展性很强。优点此处不再一一赘述。 下面介绍一些概念性知识,帮助大家理解scrapy。 一、数据流向 要想熟练掌握这个框架,一定要明...

BP神经网络原理及Python实现代码

BP神经网络原理及Python实现代码

本文主要讲如何不依赖TenserFlow等高级API实现一个简单的神经网络来做分类,所有的代码都在下面;在构造的数据(通过程序构造)上做了验证,经过1个小时的训练分类的准确率可以达到97...

Python多线程和队列操作实例

Python3,开一个线程,间隔1秒把一个递增的数字写入队列,再开一个线程,从队列中取出数字并打印到终端 复制代码 代码如下: #! /usr/bin/env python3 impor...

用Python计算三角函数之acos()方法的使用

 acos()方法返回x的反余弦值,以弧度表示。 语法 以下是acos()方法的语法: acos(x) 注意:此函数是无法直接访问的,所以我们需要导入math模块,然...