Test Content
This is a test paragraph.
如果使用BeautifulSoup时无法按照id提取数据,可能是ID中包含多个空格,或者大小写不正确造成的。我们可以在提取id时加上属性选择器来解决这个问题。例如:
from bs4 import BeautifulSoup
html_doc = """
Test Page
Test Content
This is a test paragraph.
"""
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.find('div', {'id': 'content'}).text)
这里我们使用了 find
方法和属性选择器 { 'id': 'content' }
来提取 标签中
id
为 content
的数据。这样就能避免ID中空格或大小写不一致产生的问题。
相关内容