BeautifulSoup select方法

 1 html = """
 2 <html><head><title>The Dormouse‘s story</title></head>
 3 <body>
 4 <p class="title" name="dromouse"><b>The Dormouse‘s story</b></p>
 5 <p class="story">Once upon a time there were three little sisters; and their names were
 6 <a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
 7 <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
 8 <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
 9 and they lived at the bottom of a well.</p>
10 <p class="story">...</p>
11 """

我们在写 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" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" 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" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

(3)通过 id 名查找

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

(4)组合查找

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

print soup.select(‘p #link1‘)
#[<a class="sister" href="http://example.com/elsie" 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"]‘)
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

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

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

示例代码:
from bs4 import BeautifulSoup
import requests

#定义58同城上杭州区域的起始页面
start_url = ‘http://hz.58.com/sale.shtml‘
url_host = ‘http://hz.58.com‘

def get_index_url(url):
    wb_data = requests.get(start_url)
    soup = BeautifulSoup(wb_data.text,‘lxml‘)
    links = soup.select(‘ul.ym-mainmnu > li > span > a‘)
    print(links)
    for link in links:
        page_url = url_host + str(link.get(‘href‘))
        print(page_url)
get_index_url(start_url)

运行结果:

C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Spider/58spider/channel_extact.py
[<a href="/shouji/">手机</a>, <a href="/tongxunyw/">通讯</a>, <a href="/danche/">摩托车</a>, <a href="/diandongche/">电动车</a>, <a href="/diannao/">电脑</a>, <a href="/shuma/">数码</a>, <a href="/jiadian/">家电</a>, <a href="/ershoujiaju/">家具</a>, <a href="/yingyou/">母婴玩具</a>, <a href="/fushi/">服装箱包</a>, <a href="/meirong/">美容保健</a>, <a href="/yishu/">艺术收藏</a>, <a href="/tushu/">图书音像</a>, <a href="/wenti/">文体户外</a>, <a href="/bangong/">办公设备</a>, <a href="/shebei.shtml">二手设备</a>, <a href="/chengren/" onclick="clickLog(‘from=pc_index_loucengdb_ershoujiaoyi_gongcheng‘)">成人用品</a>, <a>更多分类</a>]
http://hz.58.com/shouji/
http://hz.58.com/tongxunyw/
http://hz.58.com/danche/
http://hz.58.com/diandongche/
http://hz.58.com/diannao/
http://hz.58.com/shuma/
http://hz.58.com/jiadian/
http://hz.58.com/ershoujiaju/
http://hz.58.com/yingyou/
http://hz.58.com/fushi/
http://hz.58.com/meirong/
http://hz.58.com/yishu/
http://hz.58.com/tushu/
http://hz.58.com/wenti/
http://hz.58.com/bangong/
http://hz.58.com/shebei.shtml
http://hz.58.com/chengren/
http://hz.58.comNone

Process finished with exit code 0
时间: 2024-08-29 17:01:19

BeautifulSoup select方法的相关文章

[转]dataTable select() 方法

DataTable是我们在进行开发时经常用到的一个类,并且经常需要对DataTable中的数据进行筛选等操作,下面就介绍一下Datatable中经常用到的一个方法——Select,微软提供了四个函数的重载,分别是 Select() Select(string filterExpression) Select(string filterExpression, string sort) Select(string filterExpression,string sort, DataViewRowSt

匿名类型与Select方法实现自定义对象插入局部表结构中

在提取局部表结构数据时,通过Select选取需要的字段,如下句,此时其实产生了一个不用于_menuMan的原新数据类型new { c.SYS_COMMANDS_ID,c.TXT_COMMANDTITLE },这样的类型就叫匿名类型 var comdList = _menuMan.Load(c => c.FATHER_ID == null).OrderBy(c=>c.VAL_DISPLAYORDERID).Select(c=>new { c.SYS_COMMANDS_ID,c.TXT_CO

Thinkphp中的volist标签(查询数据集(select方法)的结果输出)用法简介

参考网址:http://camnpr.com/archives/1515.html 通常volist标签多用于查询数据集(select方法)的结果输出,通常模型的select方法返回的结果是一个二维数组,对此可以直接使用volist标签进行输出. 在控制器中首先对模版赋值,如下例所示: view sourceprint?1 $User = M('User'); 2 $list = $User->limit(10)->select(); 3 $this->assign('list',$li

C# DataTable的Select()方法不支持 != 判断

异常描述: 用户代码未处理 System.Data.SyntaxErrorExceptionHResult=-2146232032Message=无法解释位置 23 的标记“!”.Source=System.DataStackTrace:在 System.Data.ExpressionParser.Scan()在 System.Data.ExpressionParser.Parse()在 System.Data.DataExpression..ctor(DataTable table, Stri

【jQuery源码】select方法

1 /** 2 * select方法是Sizzle选择器包的核心方法之一,其主要完成下列任务: 3 * 1.调用tokenize方法完成对选择器的解析 4 * 2.对于没有初始集合(即seed没有赋值)且是单一块选择器(即选择器字符串中没有逗号), 5 * 完成下列事项: 6 * 1) 对于首选择器是ID类型且context是document的,则直接获取对象替代传入的context对象 7 * 2) 若选择器是单一选择器,且是id.class.tag类型的,则直接获取并返回匹配的DOM元素 8

C#下用select方法实现socket服务端

select是一种比较古老但一直被证明性能很好的socket模式,它可以让你以消息驱动的模式书写socket程序.网上C++的例子很多,但C#的例子极少. 上代码: namespace Server { class Program { // Thread signal. public static ManualResetEvent allDone = new ManualResetEvent(false); private static Socket handler = null; privat

DataTable 使用Select方法查询并排序,以及【拼接转义符的问题】

关于DataTable 里面用 /转义符拼接的问题 //这种写法表面上是正确,实现上在运行时调用Select方法实行查询会报错 string str = resetstrWhere + "\"" + "," + "\"" + dataQuery.DefaultOrderByClause; table = table.Select(str).CopyToDataTable(); //这种写法表面上是正确,实现上在运行时调用Sel

getField()和select()方法的区别

在ThinkPHP中,查询数据库是必不可少的操作. 那么,getField()方法和select()方法都是查询的方法,到底有什么不同呢? 案例来说明: A.select()方法 例子1 1 $access=M('access')->where(array('role_id'=>$rid))->select(); 2 dump($access); 3 die; 例子1的输出结果:二维数组 B.getField()方法 例子2:只获取node_id并组合成一维数组 1 $access=M(

HTML DOM select() 方法

定义和用法 select() 方法用于选择该元素中的文本. 语法 textareaObject.select() 实例 下面的例子可选择文本框中的文本: <html> <head> <script type="text/javascript"> function selText() { document.getElementById("txt1").select() } </script> </head>