我怎样才能在其BeautifulSoup属性匹配的文本抢元素 [英] How can I grab the element by matching text in its attribute in BeautifulSoup

查看:307
本文介绍了我怎样才能在其BeautifulSoup属性匹配的文本抢元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code

<a title="Next Page - Results 1 to 60 " href="bla bla" class="smallfont" rel="next">&gt;</a>

我要抢 A 元素,并获得在href。

I want to grab the a element and get the href .

我怎么能匹配标题带属性下一页

我想在 A 元素的title属性的文字部分匹配。

I want to partially match the text in title attribute of the a element.

有许多页面上的标签相似,但唯一不同的是,标题属性包含下页或文字方式&gt;

There are many a tags on the page similar to it but only difference is that the title attribute contains "Next Page or the text is >.

推荐答案

您必须使用正则表达式为完成你想要的东西。

You would have to use Regex for accomplishing what you want.

先取整标记为一个字符串,使 BeautifulSoup 对象吧。

First take the entire markup as a string and make a BeautifulSoup object with it.

然后使用 BeautifulSoup 对象的 .findAll 方法如下:

Then use the .findAll method of the BeautifulSoup object as follows

import BeautifulSoup
import re

soup = BeautifulSoup('<html> your markup </html>')

elements = soup.findAll('a', {'title':re.compile('Next Page.'}) 
# get all 'a' elements with 'title' attribute as 'Next Page something' into a list

for e in elements:
    if str(e.string) == '>': # check if string inside 'a' tag is '>'
        print e['href']

这篇关于我怎样才能在其BeautifulSoup属性匹配的文本抢元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆