【问题标题】:select method in BeautifulSoup not able to select attribute value with white spaceBeautifulSoup 中的选择方法无法选择带有空格的属性值
【发布时间】:2015-12-15 04:28:33
【问题描述】:
city = soup.select('a[href="/city/london d12"]')

上面的代码得到一个错误信息:

ValueError:不支持或无效的 CSS 选择器:“a[href=/city/london”

我想知道是否有解决方法或替代美味汤的方法?

<a title="London" href="/city/london d12">london</a>

【问题讨论】:

    标签: python html beautifulsoup html-parsing


    【解决方案1】:

    您必须将属性值括在双引号中

    a[href="/city/london d12"]
    

    不过,BeautifulSoup 似乎将此特定选择器标识为“无效”。这是因为BeautifulSoup supports only basic CSS selectors:

    这对于了解 CSS 选择器语法的用户来说都是一种便利。 您可以使用 Beautiful Soup API 完成所有这些工作。如果 CSS 选择器就是你所需要的,你还不如直接使用 lxml:它是 速度更快,并且它支持更多的 CSS 选择器。但这让你 将简单的 CSS 选择器与 Beautiful Soup API 相结合。

    让我们听从建议,直接使用lxml+cssselect

    >>> from lxml.cssselect import CSSSelector
    >>> from lxml.etree import fromstring
    >>> 
    >>> sel = CSSSelector('a[href="/city/london d12"]')
    >>>
    >>> tree = fromstring('<a title="London" href="/city/london d12">london</a>')
    >>> sel(tree)
    [<Element a at 0x100dad878>]
    

    你也可以使用部分属性匹配

    soup.select('a[href*=london]')  # contains "london"
    soup.select('a[href$=d12]')  # ends with "d12"
    soup.select('a[href^=/city/london]')  # starts with "city/london"
    

    【讨论】:

    • 对不起,我忘记在帖子中附上属性值,但它已附在我的代码中。问题依旧
    • 非常感谢。其实我已经用变量替换了实际值city = soup.select('a[href=%s]'%cityurl)cityurl = "/city/london d12"我的代码遍历cityurl列表来获取指定元素的文本节点
    • @XuzhengWang,顺便说一句,你也可以在这里使用find_all()find_all("a", href="/city/london d12")
    猜你喜欢
    • 1970-01-01
    • 2010-10-19
    • 2015-01-04
    • 2020-08-16
    • 2021-06-20
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多