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程序设计有所帮助。

相关文章

Django中实现点击图片链接强制直接下载的方法

本文实例讲述了Django中实现点击图片链接强制直接下载的方法。分享给大家供大家参考。具体分析如下: 当用户点击图片连接时,默认为在浏览器中直接开打图片,这段代码可以让图片链接变成下载...

Python 图像对比度增强的几种方法(小结)

Python 图像对比度增强的几种方法(小结)

图像处理工具——灰度直方图 灰度直方图时图像灰度级的函数,用来描述每个灰度级在图像矩阵中的像素个数或者占有率。 例子:矩阵 图片来自网络,侵删! 上面图片的灰度直方图 p...

Python3.5 处理文本txt,删除不需要的行方法

Python3.5 处理文本txt,删除不需要的行方法

这个问题是在问答里看到的,给了回答顺便在这里贴一下代码: #coding:utf-8 #python3.5.1 import re file_path0 = r'G:\任务201...

如何通过python画loss曲线的方法

如何通过python画loss曲线的方法

1. 首先导入一些python画图的包,读取txt文件,假设我现在有两个模型训练结果的records.txt文件 import numpy as np import matplotl...

python3对拉勾数据进行可视化分析的方法详解

python3对拉勾数据进行可视化分析的方法详解

前言 上回说到我们如何把拉勾的数据抓取下来的,既然获取了数据,就别放着不动,把它拿出来分析一下,看看这些数据里面都包含了什么信息。 (本次博客源码地址:https://github.co...