python - 将打印结果存储在 Python 的数据框中

标签 python python-3.x pandas dataframe web-scraping

我想从网络获取所有 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/

相关文章:

python - Pandas 迭代行并从另一列中删除一列中的字符串值

python - 为什么 Theano 测试会因许多 "KnownFailureTest"而失败?

Python:导入 urllib.quote

python - 连接并填充 Pandas 中缺失的列

python - 如何计算 DataFrame 中连续 TRUE 的数量?

python - 如何使用 GitHub API 获取 Python 存储库中需求文件的路径?

python - Python 中最短的数独求解器 - 它是如何工作的?

python - 带有 namedtuple() 的内部类

python - Pandas 如何删除包含所需字符串的行

python - 通过两个字符串名称过滤具有非常量形状的数据框 - Pandas