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

yipeiwu_com5年前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制作爬虫并将抓取结果保存到excel中

python制作爬虫并将抓取结果保存到excel中

学习Python也有一段时间了,各种理论知识大体上也算略知一二了,今天就进入实战演练:通过Python来编写一个拉勾网薪资调查的小爬虫。 第一步:分析网站的请求过程 我们在查看拉勾网上的...

Python 通过requests实现腾讯新闻抓取爬虫的方法

Python 通过requests实现腾讯新闻抓取爬虫的方法

最近也是学习了一些爬虫方面的知识。以我自己的理解,通常我们用浏览器查看网页时,是通过浏览器向服务器发送请求,然后服务器响应以后返回一些代码数据,再经过浏览器解析后呈现出来。而爬虫则是通过...

python网络爬虫学习笔记(1)

本文实例为大家分享了python网络爬虫的笔记,供大家参考,具体内容如下 (一)   三种网页抓取方法 1、 正则表达式: 模块使用C语言编写,速度快,但...

Python网络爬虫项目:内容提取器的定义

Python网络爬虫项目:内容提取器的定义

1. 项目背景 在python 即时网络爬虫项目启动说明中我们讨论一个数字:程序员浪费在调测内容提取规则上的时间,从而我们发起了这个项目,把程序员从繁琐的调测规则中解放出来,投入到更高...

Python爬虫 批量爬取下载抖音视频代码实例

Python爬虫 批量爬取下载抖音视频代码实例

这篇文章主要为大家详细介绍了python批量爬取下载抖音视频,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 项目源码展示: ''' 在学习过程中有什么不懂得可以加我的 pyth...