我想从网络获取所有 URL,并将结果存储为变量。到目前为止,我找到了以下代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("https://www.sport.es/") # Insert your URL to extract
bsObj = BeautifulSoup(html.read());
for link in bsObj.find_all('a'):
print(link.get('href'))
结果正是我想要的,但我需要将其存储为变量来构建数据框。我该怎么做?
谢谢大家。
最诚挚的问候,
最佳答案
首先,构建链接列表。您可以在 for
循环中附加到一个空列表:
list_of_links = []
for link in bsObj.find_all('a'):
list_of_links.append(link.get('href'))
或者,更简洁地说,您可以使用列表理解:
list_of_links = [link.get('href') for link in bsObj.find_all('a')]
然后您可以通过字典将列表提供给 pd.DataFrame
构造函数:
import pandas as pd
df = pd.DataFrame({'links': list_of_links})
关于python - 将打印结果存储在 Python 的数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51477367/