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

相关文章

浅谈Scrapy框架普通反爬虫机制的应对策略

简单低级的爬虫速度快,伪装度低,如果没有反爬机制,它们可以很快的抓取大量数据,甚至因为请求过多,造成服务器不能正常工作。而伪装度高的爬虫爬取速度慢,对服务器造成的负担也相对较小。 爬虫与...

Python网络爬虫与信息提取(实例讲解)

Python网络爬虫与信息提取(实例讲解)

课程体系结构: 1、Requests框架:自动爬取HTML页面与自动网络请求提交 2、robots.txt:网络爬虫排除标准 3、BeautifulSoup框架:解析HTML页面 4、R...

详解Python3网络爬虫(二):利用urllib.urlopen向有道翻译发送数据获得翻译结果

详解Python3网络爬虫(二):利用urllib.urlopen向有道翻译发送数据获得翻译结果

上一篇内容,已经学会了使用简单的语句对网页进行抓取。接下来,详细看下urlopen的两个重要参数url和data,学习如何发送数据data 一、urlopen的url参数 Agent...

Python爬虫设置代理IP(图文)

Python爬虫设置代理IP(图文)

在爬虫的过程中,我们经常会遇见很多网站采取了防爬取技术,或者说因为自己采集网站信息的强度和采集速度太大,给对方服务器带去了太多的压力。 如果你一直用同一个代理ip爬取这个网页,很有可能i...

Python制作简单的网页爬虫

1.准备工作: 工欲善其事必先利其器,因此我们有必要在进行Coding前先配置一个适合我们自己的开发环境,我搭建的开发环境是: 操作系统:Ubuntu 14.04 LTS Pytho...