在使用find_all()函数时,返回的是一组可迭代对象,如果需要将这些对象存储到一个列表中,可以使用append()函数来实现。但这种方法会创建一个二维列表,而不是一个一维列表。例如:
from bs4 import BeautifulSoup
html_doc = """The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
Elsie,
Lacie and
Tillie;
and they lived at the bottom of a well.
"""
soup = BeautifulSoup(html_doc, 'html.parser')
links = []
for link in soup.find_all('a'):
links.append(link.get('href'))
print(links)
输出结果为:
['http://example.com/elsie', 'http://example.com/lacie', 'http://example.com/tillie']
如果想将结果存储到一个一维列表中,可以使用extend()函数代替append()函数,如下所示:
links = []
for link in soup.find_all('a'):
links.extend([link.get('href')])
print(links)
输出结果为:
['http://example.com/elsie', 'http://example.com/lacie', 'http://example.com/tillie']
这样就能创建一个一维列表了。