python爬虫之BeautifulSoup 使用select方法详解

本文介绍了python爬虫之BeautifulSoup 使用select方法详解 ,分享给大家。具体如下:

<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" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""

我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list

(1)通过标签名查找

print soup.select('title')
#[<title>The Dormouse's story</title>]

print soup.select('a')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]

print soup.select('b')
#[<b>The Dormouse's story</b>]

(2)通过类名查找

print soup.select('.sister')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]

(3)通过 id 名查找

print soup.select('#link1')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>]

(4)组合查找

组合查找即和写 class 文件时,标签名与类名、id名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开

print soup.select('p #link1')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>]

直接子标签查找

print soup.select("head > title")
#[<title>The Dormouse's story</title>]

(5)属性查找

查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。

print soup.select("head > title")
#[<title>The Dormouse's story</title>]

print soup.select('a[href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ]')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>]

同样,属性仍然可以与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格

print soup.select('p a[href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ]')
#[<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1"><!-- Elsie --></a>]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 基于python select.select模块通信的实例讲解

    要理解select.select模块其实主要就是要理解它的参数, 以及其三个返回值. select()方法接收并监控3个通信列表, 第一个是所有的输入的data,就是指外部发过来的数据,第2个是监控和接收所有要发出去的data(outgoing data),第3个监控错误信息在网上一直在找这个select.select的参数解释, 但实在是没有, 哎...自己硬着头皮分析了一下. readable, writable, exceptional = select.select(inputs, ou

  • 深入理解python中的select模块

    简介 Python中的select模块专注于I/O多路复用,提供了select  poll  epoll三个方法(其中后两个在Linux中可用,windows仅支持select),另外也提供了kqueue方法(freeBSD系统) select方法 进程指定内核监听哪些文件描述符(最多监听1024个fd)的哪些事件,当没有文件描述符事件发生时,进程被阻塞:当一个或者多个文件描述符事件发生时,进程被唤醒. 当我们调用select()时: 1.上下文切换转换为内核态 2.将fd从用户空间复制到内核空

  • pycharm 使用心得(九)解决No Python interpreter selected的问题

    初次安装完PyCharm后,新建项目时,遇到了No Python interpreter selected的问题. 意思是说没有找到Python解释器.那我们添加Python解释器即可. Python–Preferences–Project Interpreter–Python Interpreter 点击"+"号选择系统安装的Python. 然后再返回Project Interpreter,选择刚添加的解释器. 现在就能新建项目了. 开始你的Python之旅吧.

  • python select.select模块通信全过程解析

    要理解select.select模块其实主要就是要理解它的参数, 以及其三个返回值. select()方法接收并监控3个通信列表, 第一个是所有的输入的data,就是指外部发过来的数据,第2个是监控和接收所有要发出去的data(outgoing data),第3个监控错误信息 在网上一直在找这个select.select的参数解释, 但实在是没有, 哎...自己硬着头皮分析了一下. readable, writable, exceptional = select.select(inputs, o

  • Python基于select实现的socket服务器

    本文实例讲述了Python基于select实现的socket服务器.分享给大家供大家参考,具体如下: 借鉴了asyncore模块中select.select的使用方法 import socket import traceback import select EOL1 = b'\n\n' EOL2 = b'\n\r\n' socketmap = {} r,w,e = [],[],[] response = b'HTTP/1.0 200 OK\r\nDate: Mon, 1 Jan 1996 01:

  • Python通过select实现异步IO的方法

    本文实例讲述了Python通过select实现异步IO的方法.分享给大家供大家参考.具体如下: 在Python中使用select与poll比起在C中使用简单得多.select函数的参数是3个列表,包含整数文件描述符,或者带有可返回文件描述符的fileno()方法对象.第一个参数是需要等待输入的对象,第二个指定等待输出的对象,第三个参数指定异常情况的对象.第四个参数则为设置超时时间,是一个浮点数.指定以秒为单位的超时值.select函数将会返回一组文件描述符,包括输入,输出以及异常. 在linux

  • Python的Django框架中的select_related函数对QuerySet 查询的优化

    1. 实例的背景说明 假定一个个人信息系统,需要记录系统中各个人的故乡.居住地.以及到过的城市.数据库设计如下: Models.py 内容如下: from django.db import models class Province(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return self.name class City(models.Model): name = models

  • Python中使用select模块实现非阻塞的IO

    Socket的英文原义是"孔"或"插座".作为BSD UNIX的进程通信机制,取后一种意思.通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄.在Internet上的主机一般运行了多个服务软件,同时提供几种服务.每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务.Socket正如其英文原意那样,像一个多孔插座.一台主机犹如布满各种插座的房间,每个插座有一个编号,有的插座提供220伏交流电, 有的提供110

  • 总结网络IO模型与select模型的Python实例讲解

    网络I/O模型 人多了,就会有问题.web刚出现的时候,光顾的人很少.近年来网络应用规模逐渐扩大,应用的架构也需要随之改变.C10k的问题,让工程师们需要思考服务的性能与应用的并发能力. 网络应用需要处理的无非就是两大类问题,网络I/O,数据计算.相对于后者,网络I/O的延迟,给应用带来的性能瓶颈大于后者.网络I/O的模型大致有如下几种: 同步模型(synchronous I/O) 阻塞I/O(bloking I/O) 非阻塞I/O(non-blocking I/O) 多路复用I/O(multi

  • python爬虫之BeautifulSoup 使用select方法详解

    本文介绍了python爬虫之BeautifulSoup 使用select方法详解 ,分享给大家.具体如下: <html><head><title>The Dormouse's story</title></head> <body> <p class="title" name="dromouse"><b>The Dormouse's story</b></

  • Python爬虫进阶之Beautiful Soup库详解

    一.Beautiful Soup库简介 BeautifulSoup4 是一个 HTML/XML 的解析器,主要的功能是解析和提取 HTML/XML 的数据.和 lxml 库一样. lxml 只会局部遍历,而 BeautifulSoup4 是基于 HTML DOM 的,会加载整个文档,解析 整个 DOM 树,因此内存开销比较大,性能比较低. BeautifulSoup4 用来解析 HTML 比较简单,API 使用非常人性化,支持 CSS 选择器,是 Python 标准库中的 HTML 解析器,也支

  • Python爬虫库urllib的使用教程详解

    目录 Python urllib库 urllib.request模块 urlopen函数 Request 类 urllib.error模块 URLError 示例 HTTPError示例 URLError和HTTPError混合使用 urllib.parse模块 urlparse() urlunparse() urlsplit() urljoin() URL 转码 编码quote(string) 编码urlencode() 解码 unquote(string) urllib.robotparse

  • Python爬虫urllib和requests的区别详解

    我们讲了requests的用法以及利用requests简单爬取.保存网页的方法,这节课我们主要讲urllib和requests的区别. 1.获取网页数据 第一步,引入模块. 两者引入的模块是不一样的,这一点显而易见. 第二步,简单网页发起的请求. urllib是通过urlopen方法获取数据. requests需要通过网页的响应类型获取数据. 第三步,数据封装. 对于复杂的数据请求,我们只是简单的通过urlopen方法肯定是不行的.最后,如果你的时间不是很紧张,并且又想快速的提高,最重要的是不怕

  • 对python pandas 画移动平均线的方法详解

    数据文件 66001_.txt 内容格式: date,jz0,jz1,jz2,jz3,jz4,jz5 2012-12-28,0.9326,0.8835,1.0289,1.0027,1.1067,1.0023 2012-12-31,0.9435,0.8945,1.0435,1.0031,1.1229,1.0027 2013-01-04,0.9403,0.8898,1.0385,1.0032,1.1183,1.0030 ... ... pd_roll_mean1.py # -*- coding: u

  • 对python dataframe逻辑取值的方法详解

    我遇到的一个小需求,就是希望通过判断pandas dataframe中一列的值在两个条件范围(比如下面代码中所描述的逻辑,取小于u-3ε和大于u+3ε的值),然后取出dataframe中的所有符合条件的值,这个需求的解决与普通的iloc.loc.ix的方式不同,所以我想分享一下,希望可以帮到遇到这个困难的朋友们,下面是我的实例代码: doc[~((doc.iloc[:,141:142]<(mean_value-3*std_value))&(doc.iloc[:,141:142]>(me

  • 对Python获取屏幕截图的4种方法详解

    Python获取电脑截图有多种方式,具体如下: PIL中的ImageGrab模块 windows API PyQt pyautogui PIL中的ImageGrab模块 import time import numpy as np from PIL import ImageGrab img = ImageGrab.grab(bbox=(100, 161, 1141, 610)) img = np.array(img.getdata(), np.uint8).reshape(img.size[1]

  • 对Python的多进程锁的使用方法详解

    很多时候,我们需要在多个进程中同时写一个文件,如果不加锁机制,就会导致写文件错乱 这个时候,我们可以使用multiprocessing.Lock() 我一开始是这样使用的: import multiprocessing lock = multiprocessing.Lock() class MatchProcess(multiprocessing.Process): def __init__(self, threadId, mfile, lock): multiprocessing.Proces

  • 对Python之gzip文件读写的方法详解

    gzip文件读写的时候需要用到Python的gzip模块. 具体使用如下: # -*- coding: utf-8 -*- import gzip # 写文件 f_out = gzip.open("xxx.gz", "wb") # 读文件 # f_in = gzip.open("xxx.gz", "rb") for line in open("yyy.txt", "rb"): f_out

  • 对Python定时任务的启动和停止方法详解

    在python中我们可以使用APScheduler进行定时任务. APScheduler的具体编码这里就不介绍了.主要说下在终端中启动和停止任务. 一.运行计划任务的python脚本 如果我们在终端中直接执行的话,关闭终端窗口,Python任务就会中断,Python进程会被杀死,程序将停止运行.可以使用如下命令运行python脚本, python apschedulerscript.py & 这样执行后及时关闭终端窗口,程序依旧运行. 二.停止计划任务的Python脚本 如何停止呢,可使用如下方

随机推荐