Using: bs4, Python3.9, lxml
假设我有一些像这样的HTML:
<div>
<a href="google.com">Item 3</a>
<a href="facebook.com">Item 3</a>
</div>
我想找到单词Item 3
的第一次出现,并获得特定的<a>
标签和它指向的链接。我该怎么做呢?谢谢!
使用.find()
方法将返回它找到的第一个实例。因此,只需查找具有给定文本的<a>
标记,并取出href属性:
from bs4 import BeautifulSoup
html = '''<div>
<a href="google.com">Item 3</a>
<a href="facebook.com">Item 3</a>
</div>'''
soup = BeautifulSoup(html, 'html.parser')
item3 = soup.find('a', text='Item 3')['href']
输出:
print (item3)
google.com
可以使用xpath:
from lxml import etree
root = etree.fromstring(html_doc)
e = root.xpath('.//a[text()="TEXT B"]')
输出:
print(e.text)
TEXT B
您可以使用.find
和text=
属性lambda:
from bs4 import BeautifulSoup
html_doc = """
<div>
<a href="google.com">Item 3</a>
<a href="facebook.com">Item 3</a>
</div>
"""
soup = BeautifulSoup(html_doc, "html.parser")
to_search = "Item 3"
tag = soup.find(text=lambda t: to_search in t).parent
print(tag)
打印:
<a href="google.com">Item 3</a>
或者:Using CSS selector:
a = soup.select_one('a:-soup-contains("Item 3")')
print(a)
print(a["href"])
打印:
<a href="google.com">Item 3</a>
google.com