可以使用常用的爬虫库(如 Beautiful Soup)对网页进行解析,然后使用 find() 或 find_all() 方法查找包含特定文本的标签。例如,使用 Beautiful Soup 解析网页后,可以使用 find_all() 方法查找所有包含特定文本的
标签。代码如下:
from bs4 import BeautifulSoup
html = '<p>example text1</p><p>example text 2</p>'
soup = BeautifulSoup(html, 'html.parser')
tags = soup.find_all('p', string='example text 1')
find_all 参数可以指定查找的标签以及附带的文字
另外, 也可以通过使用CSS selector, XPath 使用特定工具来查询页面控件, 比如 selenium
如:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")
elem = driver.find_element_by_xpath("//*[contains(text(),'Python')]")
这个例子找到了页面上文字包含"Python"的所有标签