繁体   English   中英

使用带有BeutifulSoup的CSS选择器获取属性值

[英]Get value of attribute using CSS Selectors with BeutifulSoup

我正在使用Python进行网络BeutifulSoup并使用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-urlhref值。 如果我能获得href价值,那就更好了

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

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"])

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM