python3 BeautifulSoup模块使用字典的方法抓取a标签内的数据示例

yipeiwu_com6年前Python爬虫

本文实例讲述了python3 BeautifulSoup模块使用字典的方法抓取a标签内的数据。分享给大家供大家参考,具体如下:

# -*- coding:utf-8 -*-
#python 2.7
#XiaoDeng
#http://tieba.baidu.com/p/2460150866
#标签操作
from bs4 import BeautifulSoup
import urllib.request
import re
#如果是网址,可以用这个办法来读取网页
#html_doc = "http://tieba.baidu.com/p/2460150866"
#req = urllib.request.Request(html_doc) 
#webpage = urllib.request.urlopen(req) 
#html = webpage.read()
html="""
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" class="sister" id="xiaodeng"><!-- Elsie --></a>,
<a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow" class="sister" id="link3">Tillie</a>;
<a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" class="sister" id="xiaodeng">Lacie</a>
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html, 'html.parser') #文档对象
#查找a标签,只会查找出一个a标签
#print(soup.a)#<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" id="xiaodeng"><!-- Elsie --></a>
for k in soup.find_all('a'):
 print(k)
 print(k['class'])#查a标签的class属性
 print(k['id'])#查a标签的id值
 print(k['href'])#查a标签的href值
 print(k.string)#查a标签的string
#如果,标签中含有其他标签,比如..,此时要提取中的数据,需要用k.get_text()
#tag.get('calss'),也可以达到这个效果

Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

更多关于Python相关内容可查看本站专题:《

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

相关文章

Python爬取京东的商品分类与链接

Python爬取京东的商品分类与链接

前言 本文主要的知识点是使用Python的BeautifulSoup进行多层的遍历。 如图所示。只是一个简单的哈,不是爬取里面的隐藏的东西。 示例代码 from bs4 impor...

Python3实现爬取指定百度贴吧页面并保存页面数据生成本地文档的方法

分享给大家供大家参考,具体如下:Python3实现爬取指定百度贴吧页面并保存页面数据生成本地文档的方法。分享给大家供大家参考,具体如下: 首先我们创建一个python文件, tieba....

Python爬取视频(其实是一篇福利)过程解析

窗外下着小雨,作为单身程序员的我逛着逛着发现一篇好东西,来自知乎 你都用 Python 来做什么?的第一个高亮答案。 到上面去看了看,地址都是明文的,得,赶紧开始吧。 下载流式文件,re...

使用Python的Scrapy框架十分钟爬取美女图

使用Python的Scrapy框架十分钟爬取美女图

简介 scrapy 是一个 python 下面功能丰富、使用快捷方便的爬虫框架。用 scrapy 可以快速的开发一个简单的爬虫,官方给出的一个简单例子足以证明其强大: 快速开发 下面开...

几行Python代码爬取3000+上市公司的信息

几行Python代码爬取3000+上市公司的信息

前言 入门爬虫很容易,几行代码就可以,可以说是学习 Python 最简单的途径。 刚开始动手写爬虫,你只需要关注最核心的部分,也就是先成功抓到数据,其他的诸如:下载速度、存储方式、代码条...