python 如何获取页面所有a标签下href的值

看代码吧~

# -*- coding:utf-8 -*-
#python 2.7
#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
    

如果,标签<a>中含有其他标签,比如<em>..</em>,此时要提取<a>中的数据,需要用k.get_text()

soup = BeautifulSoup(html, 'html.parser')   #文档对象
#查找a标签,只会查找出一个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

如果,标签<a>中含有其他标签,比如<em>..</em>,此时要提取<a>中的数据,需要用k.get_text()

通常我们使用下面这种模式也是能够处理的,下面的方法使用了get()。

 html = urlopen(url)
 soup = BeautifulSoup(html, 'html.parser')
 t1 = soup.find_all('a')
 print t1
 href_list = []
 for t2 in t1:
    t3 = t2.get('href')
    href_list.append(t3)

补充:python爬虫获取任意页面的标签和属性(包括获取a标签的href属性)

看代码吧~

# coding=utf-8
from bs4 import BeautifulSoup
import requests
# 定义一个获取url页面下label标签的attr属性的函数
def getHtml(url, label, attr):
    response = requests.get(url)
    response.encoding = 'utf-8'
    html = response.text
    soup = BeautifulSoup(html, 'html.parser');
    for target in soup.find_all(label):

        try:
            value = target.get(attr)

        except:
            value = ''

        if value:
            print(value)

url = 'https://baidu.com/'
label = 'a'
attr = 'href'
getHtml(url, label, attr)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

(0)

相关推荐

  • python3爬虫获取html内容及各属性值的方法

    今天用到BeautifulSoup解析爬下来的网页数据 首先导入包from bs4 import BeautifulSoup 然后可以利用urllib请求数据 记得要导包 import urllib.request 然后调用urlopen,读取数据 f=urllib.request.urlopen('http://jingyan.baidu.com/article/455a9950bc94b8a166277898.html') response=f.read() 这里我们就不请求数据了,直接用本

  • python selenium 获取标签的属性值、内容、状态方法

    获取标签内容 使用element.attribute()方法获取dom元素的内容,如: dr = driver.find_element_by_id('tooltip') dr.get_attribute('data-original-title') #获取tooltip的内容 dr.text #获取该链接的text 获取标签属性 link=dr.find_element_by_id('tooltip') link.value_of_css_property('color') #获取toolti

  • Python爬虫获取页面所有URL链接过程详解

    如何获取一个页面内所有URL链接?在Python中可以使用urllib对网页进行爬取,然后利用Beautiful Soup对爬取的页面进行解析,提取出所有的URL. 什么是Beautiful Soup? Beautiful Soup提供一些简单的.python式的函数用来处理导航.搜索.修改分析树等功能.它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序. Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换

  • Python爬虫库BeautifulSoup获取对象(标签)名,属性,内容,注释

    一.Tag(标签)对象 1.Tag对象与XML或HTML原生文档中的tag相同. from bs4 import BeautifulSoup soup = BeautifulSoup('<b class="boldest">Extremely bold</b>','lxml') tag = soup.b type(tag) bs4.element.Tag 2.Tag的Name属性 每个tag都有自己的名字,通过.name来获取 tag.name 'b' tag.

  • python 如何获取页面所有a标签下href的值

    看代码吧~ # -*- coding:utf-8 -*- #python 2.7 #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

  • python xpath获取页面注释的方法

    版本信息: python 2.7.12 lxml 3.8.0 from lxml import etree html_str = """ <div id="box1">this from blog.csdn.net/lncxydjq , DO NOT COPY! <div id="box2">***** <!--can u get me, bitch?--> </div> </div

  • Python get获取页面cookie代码实例

    在Python中通过GET来获取页面的COOKIE是非常简单的事情,下面的代码实例演示了如何利用Python 获取COOKIE内容 #! /usr/bin/env python #coding=utf-8 # -*-coding:utf-8 -*- #encoding=utf-8 import urllib import urllib2 import httplib cj='' header={'Host':'218.94.26.135', 'Accept-Language':'zh-CN',

  • python使用xpath获取页面元素的使用

    关于python 使用xpath获取网页信息的方法? 1.xpath的使用方法? ​ XPath 使用路径表达式来选取 XML 文档中的节点或节点集.节点是通过沿着路径 (path) 或者步 (steps) 来选取的. 常用路径表达式含义 表达式 描述 / 从根节点选取(取子节点) // 选择的当前节点选择文档中的节点 . 选取当前节点. - 选取当前节点的父节点. @ 选取属性 * 表示任意内容(通配符) | 运算符可以选取多个路径 常用功能函数 函数 用法 解释 startswith() x

  • Python Selenium自动化获取页面信息的方法

    1.获取页面title title:获取当前页面的标题显示的字段 from selenium import webdriver import time browser = webdriver.Chrome() browser.get('https://www.baidu.com') #打印网页标题 print(browser.title) #输出内容:百度一下,你就知道 2.获取页面URL current_url:获取当前页面的URL from selenium import webdriver

  • 详解BeautifulSoup获取特定标签下内容的方法

    以下是个人在学习beautifulSoup过程中的一些总结,目前我在使用爬虫数据时使用的方法的是:先用find_all()找出需要内容所在的标签,如果所需内容一个find_all()不能满足,那就用两个或者多个.接下来遍历find_all的结果,用get_txt().get('href').得到文本或者链接,然后放入各自的列表中.这样做有一个缺点就是txt的数据是一个单独的列表,链接的数据也是一个单独的列表,一方面不能体现这些数据之间的结构性,另一方面当想要获得更多的内容时,就要创建更多的空列表

  • Python正则获取、过滤或者替换HTML标签的方法

    本文实例介绍了Python通过正则表达式获取,去除(过滤)或者替换HTML标签的几种方法,具体内容如下 python正则表达式关键内容: python正则表达式转义符: . 匹配除换行符以外的任意字符 \w 匹配字母或数字或下划线或汉字 \s 匹配任意的空白符 \d 匹配数字 \b 匹配单词的开始或结束 ^ 匹配字符串的开始 $ 匹配字符串的结束 \W 匹配任意不是字母,数字,下划线,汉字的字符 \S 匹配任意不是空白符的字符 \D 匹配任意非数字的字符 \B 匹配不是单词开头或结束的位置 [^

  • Python基于lxml模块解析html获取页面内所有叶子节点xpath路径功能示例

    本文实例讲述了Python基于lxml模块解析html获取页面内所有叶子节点xpath路径功能.分享给大家供大家参考,具体如下: 因为需要使用叶子节点的路径来作为特征,但是原始的lxml模块解析之后得到的却是整个页面中所有节点的xpath路径,不是我们真正想要的形式,所以就要进行相关的处理才行了,差了很多网上的博客和文档也没有找到一个是关于输出html中全部叶子节点的API接口或者函数,也可能是自己没有那份耐心,没有找到合适的资源,只好放弃了寻找,但是这并不说明没有其他的方法了,在对页面全部节点

随机推荐