美丽的汤。如何查找包含3个属性的所有链接

时间:2016-09-13 19:30:57

标签: python-2.7 web-scraping beautifulsoup

如何使用美丽的汤找到所有具有3个属性的链接?

我想找到包含所有属性的所有链接:

a id="js_24" class="_27jf _3emk" data-hover="tooltip"

我试过这样的方式:

emo = soup.find_all('a', {'id': 'fjs_24', 'class': '_27jf _3emk', 'data-hover':"tooltip"})

但没有成功。我没有结果。

完整链接看起来如此:

<a id="js_24" class="_27jf _3emk" data-hover="tooltip" aria-label="6 Wow" href="/ufi/reaction/profile/browser/?ft_ent_identifier=909182312524600&av=100011414120311" rel="ignore" role="button" tabindex="-1">

1 个答案:

答案 0 :(得分:1)

您的逻辑没有问题,问题是 id 错误,当实际ID为fjs_24时您有js_24

emo = soup.find_all('a', {'id': 'js_24', 'class': '_27jf _3emk', 'data-hover':"tooltip"})

进行更改后,您可以看到它有效:

In [10]: from bs4 import BeautifulSoup


In [11]: soup = BeautifulSoup("""<a id="js_24" class="_27jf _3emk" data-hover="tooltip" aria-label="6 Wow" href="/ufi/reaction/profile/browser/?ft_ent_identifier=909182312524600&av=100011414120311" rel="ignore" role="button" tabindex="-1"></a>""","lxml")


In [12]: soup.find_all('a', {'id': 'fjs_24', 'class': '_27jf _3emk', 'data-hover':"tooltip"})
Out[12]: []

In [13]: soup.find_all('a', {'id': 'js_24', 'class': '_27jf _3emk', 'data-hover':"tooltip"})
Out[13]: [<a aria-label="6 Wow" class="_27jf _3emk" data-hover="tooltip" href="/ufi/reaction/profile/browser/?ft_ent_identifier=909182312524600&amp;av=100011414120311" id="js_24" rel="ignore" role="button" tabindex="-1"></a>]

如果您安装了 lxml ,则可以使用 css选择器更快,更简洁地执行此操作:

from lxml import html

tree = html.fromstring(""""<a id="js_24" class="_27jf _3emk" data-hover="tooltip" aria-label="6 Wow" href="/ufi/reaction/profile/browser/?ft_ent_identifier=909182312524600&av=100011414120311" rel="ignore" role="button" tabindex="-1"></a>""")

print(tree.cssselect("#js_24[class='_27jf _3emk'][data-hover='tooltip']"))
相关问题