使用带有BeutifulSoup的CSS选择器获取属性值 [英] Get value of attribute using CSS Selectors with BeutifulSoup

查看:58
本文介绍了使用带有BeutifulSoup的CSS选择器获取属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 并使用 BeutifulSoup

我有这样的 HTML 标记:

<tr class="deals" data-url="www.example2.com">
<span class="hotel-name">
<a href="www.example2.com"></a>
</span>
</tr>
<tr class="deals" data-url="www.example3.com">
<span class="hotel-name">
<a href="www.example3.com"></a>
</span>
</tr>

我想在所有< tr> 中都获得 data-url href 值.如果可以得到 href

I want to get the data-url or the href value in all <tr>s. Better If I can get href value

这是我相关代码的一小段:

Here is a little snippet of my relevant code:

main_url =  "http://localhost/test.htm"
page  = requests.get(main_url).text
soup_expatistan = BeautifulSoup(page)

print (soup_expatistan.select("tr.deals").data-url)
# or  print (soup_expatistan.select("tr.deals").["data-url"])

推荐答案

您可以使用 tr.deals span.hotel-name a CSS选择器访问链接:

You can use tr.deals span.hotel-name a CSS Selector to get to the link:

from bs4 import BeautifulSoup

data = """
<tr class="deals" data-url="www.example.com">
<span class="hotel-name">
<a href="wwwexample2.com"></a>
</span>
</tr>
"""

soup = BeautifulSoup(data)
print(soup.select('tr.deals span.hotel-name a')[0]['href'])

打印:

wwwexample2.com

如果您有多个链接,请对其进行迭代:

If you have multiple links, iterate over them:

for link in soup.select('tr.deals span.hotel-name a'):
    print(link['href'])

这篇关于使用带有BeutifulSoup的CSS选择器获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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