我的问题与这个问题有些相似: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相关问答推荐

Paramiko SFTPClient get()和put()函数的通过/失败结果?

如何使用regex将电话号码和姓名从文本字符串中分离出来

如何绘制交叉验证的AUROC并找到最佳阈值?

被多个\n拆分并保留

数据类对象列表的字典获取方法-在数据类列表中查找具有特定变量值的数据类

为什么空列表也能起作用?

提取图像中的背景并保存

Pandas groupby 然后 for each 组添加新行

我应该如何调整我的变量,以便如果有任何单词符合其中的条件,程序会将其附加到新列表中?

GEKKO 在没有不等式的模型中抛出不等式定义错误

Keras 中 Conv2D 层的意外结果

pytorch 中 mps 设备的 manual_seed

如何查找 tensorflow.python.data.ops.dataset_ops.MapDataset 对象的大小或形状,make_csv_dataset 的输出

`pyspark mllib` 与 `pyspark ml` 包

你如何表达一个没有参数的 Python Callable?

Python过滤器函数 - 单个结果

如何将 cv2.imread 匹配到 keras image.img_load 输出

在python中打印下标

TypeError: write() 参数必须是 str,而不是字节(Python 3 vs Python 2)

从 csv 中删除单行而不复制文件