【问题标题】:Store a printed result in a dataframe in Python在 Python 中将打印结果存储在数据框中
【发布时间】:2018-12-30 19:43:00
【问题描述】:

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

结果正是我想要的,但我需要将其存储为变量来构建数据框。我该怎么做?

谢谢大家。

最好的问候,

【问题讨论】:

  • 为什么需要将 url 存储在 pandas 数据框中?
  • 因为我需要使用存储在列中的不同变量(不仅是 url)...

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


【解决方案1】:

首先,构建一个链接列表。您可以在 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})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-22
    • 2021-09-11
    • 2020-07-11
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    相关资源
    最近更新 更多