我的问题与这个问题有些相似:How to save out in a new column the url which is reading pandas read_html() function?

我有一组包含表的链接(每个表4个,我只需要前三个).目标是将每个表的链接存储在单独的"地址"列中.

links = ['www.link1.com', 'www.link2.com', ... , 'www.linkx.com']
details = []

for link in tqdm(links):
    page = requests.get(link)
    sauce = BeautifulSoup(page.content, 'lxml')
    table = sauce.find_all('table')

    # Only first 3 tables include data
    for i in range(3):
        details.append(pd.read_html(str(table))[i])
        final_df = pd.concat(details, ignore_index=True)
        final_df['address'] = link
    time.sleep(2)

然而,当我使用这个代码时,只有最后一个链接被分配给"地址"列中的每一行.

我可能错过了一个细节,但在过go 的两个小时里,我一直在想这个问题,根本无法取得任何进展——非常感谢您的帮助.

推荐答案

你已经接近你的目标了——在每次迭代中将df['address']添加到你的DataFrame中,然后再将其添加到你的列表中:

for i in table[:3]:
    df = pd.read_html(str(i))[0]
    df['address'] = link
    details.append(df)

Note You could also slice your 100 of tables 101 so you do not have to use range

将concatation移到循环之外,如果迭代结束,则将其称为one:

final_df = pd.concat(details, ignore_index=True)

Example

import pandas as pd

links = ['www.link1.com', 'www.link2.com','www.linkx.com']
details = []

for link in links:
    # page = requests.get(link)
    # sauce = BeautifulSoup(page.content, 'lxml')
    # table = sauce.find_all('table')
    table = ['<table><tr><td>table 1</td></tr></table>',
             '<table><tr><td>table 2</td></tr></table>',
             '<table><tr><td>table 3</td></tr></table>']
    # Only first 3 tables include data
    for i in table[:3]:
        df = pd.read_html(str(i))[0]
        df['address'] = link
        details.append(df)

final_df = pd.concat(details, ignore_index=True)

Output

0 address
table 1 www.link1.com
table 2 www.link1.com
table 3 www.link1.com
table 1 www.link2.com
table 2 www.link2.com
table 3 www.link2.com
table 1 www.linkx.com
table 2 www.linkx.com
table 3 www.linkx.com

Python-3.x相关问答推荐

如何创建一个polars gramme,给出列表中的列名,

我在创建Pandas DataFrame时感到困惑

如何计算累积几何平均数?

如何获取实例化 `types.GenericAlias` 的下标类?

Python中提取每个组/ID所属特定列中的自然数

我想使用命令提示符安装 cv2

拆分列表的元素并将拆分后的元素包含到列表中

Pandas:从 Pandas 数据框中的 1 和 0 模式中获取值和 ID 的计数

!date 的命令无法从 jupyter notebook 运行

如何向 scikit-learn 函数添加类型提示?

找到操作系统的图片文件夹的 CLI

Pandas 值列中列表中元素的计数

Await Future 来自 Executor:Future 不能在await表达式中使用

django.core.exceptions.ImproperlyConfigured

为什么我在 Python 中收到错误消息无法导入名称 NoneType?

如何模拟 open(...).write() 而不会出现没有这样的文件或目录错误?

计数大于Pandas groupby 中的值的项目

计算两个文件的行差异的最有效方法是什么?

Python pathlib 获取父级相对路径

有没有一种标准方法来确保 python 脚本将由 python2 而不是 python3 解释?