使用 CSS 选择器和 BeautifulSoup 获取属性值

2024-06-25

我正在抓取网页Python并使用BeutifulSoup library

I have 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>

我想要得到data-url or the href全部价值<tr>s。如果我能得到就更好了href value

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

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 选择器:

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

Prints:

wwwexample2.com

如果您有多个链接,请迭代它们:

for link in soup.select('tr.deals span.hotel-name a'):
    print(link['href'])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 CSS 选择器和 BeautifulSoup 获取属性值 的相关文章

随机推荐