BeautifulSoup 如何在HTML文件中找到特定标签的所有出现
问题描述
在一个大的HTML文件中,我正在尝试使用BeautifulSoup返回所有具有特定标签的内容(例如: “span data-qa-id=”aditem_price””) 但我找不到答案,有人知道该怎么做吗? 我正在尝试学习一些关于爬取网站的知识
解决方案
你可以使用 find_all 方法:(正如文档中提到的,第一个参数是标签名称,第二个参数是一个属性对象)
sample_web_page = 'your_url'
page = requests.get(sample_web_page)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find_all("span", {"data-qa-id" : "aditem_price"})
如果你从文件中阅读,可以将文件对象传递给它:
with open("your_file_path") as fp:
soup = BeautifulSoup(fp, 'html.parser')
results = soup.find_all("span", {"data-qa-id" : "aditem_price"})