首页 > 解决方案 > 我可以不将美丽汤中的 .text 附加到 python DataFrame

问题描述

我正在尝试遍历 URL 列表,以使用 requests.get() 和美丽的汤从网站中提取特定文本。URL 恢复正常,我还可以打印我正在寻找的文本(电话号码),它工作正常,但是TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid当我尝试附加到以前用空 [] 创建的数据帧时收到一个。

    try:
        response = requests.get(f"https://www.yellowpages.com/search?search_terms={sc_df['Business Name'][i]}&geo_location_terms={sc_df['City'][i]}+{sc_df['State'][i]}")

        soup = BeautifulSoup(response.text, 'html.parser')

        test = soup.find('div', attrs = {'class':'info'}).find('div', attrs = {'class':'phones phone primary'})

        if test is not None:
            text = test.text
            print(str(text))

            new_number_df['Business Name'].append(sc_df['Business Name'][i])
            new_number_df['Phone'].append(text)
        else:
            test = None
            print(test)

    except requests.exceptions.RequestException as e: 
        raise SystemExit(e)```

标签: pythonbeautifulsouppython-requests

解决方案


正如你的错误所说,你

无法连接类型“<class 'str'> 的对象

所以您需要将您的添加转换为 pandas.Series 对象,然后附加它,如下所示:

new_number_df['Phone'].append(pandas.Series([text]))

希望这能解决您的问题!


推荐阅读