【问题标题】:How to assign bs4 strings to pandas dataframe in for loop?如何在for循环中将bs4字符串分配给pandas数据框?
【发布时间】:2021-01-10 21:33:47
【问题描述】:

我有一个 HTML 字符串,我可以成功地使用 beautifulsoup4 来提取我需要的元素。

HTML 字符串在一个列表中,我只想从字符串中提取某些元素并将它们分配给数据框列。

当前代码:

import pandas as pd
from bs4 import BeautifulSoup

lst = [ <html>,<html>]

df = pd.DataFrame()

for i in lst:
    soup = BeautifulSoup(i)
    
    for link in soup.find_all('a'):
        df['links'] = str(link.get('href'))
        #print(link.get('href'))
        
    #get all text messages
    soup.find_all('p')
    df['messages'] = str(soup.find_all('p'))
    
    #get author name
    soup.find_all(class_="author--name")
    df['author'] = str(soup.find_all(class_="author--name"))
    
    #get username
    soup.find_all(class_= "author--username")
    df['username'] = str(soup.find_all(class_= "author--username"))

所有代码行都在生成我需要的数据,但为什么数据框没有将字符串值分配给数据框列?

我可以从一个空数据框中看到,代码创建了新列,但没有值。

我做错了什么?

【问题讨论】:

  • 也许问题在于您如何使用数据库本身。用虚拟文本替换汤。
  • @Someone 我设置了df['links'] = 'a' 仍然没有运气。
  • 您可以编辑您的问题并添加lst 元素的示例吗?
  • 看到这个stackoverflow.com/questions/53236855/… 你可能需要传递一个列表而不是字符串。 soup.find_all('p') 返回一个列表吗?如果没有,您可以创建这些值的列表而不是使用 str() 吗?
  • @JonathanLeon @Jack 我将所有作业都括在括号中,并且有效。像这样:[str(link.get('href'))]

标签: python-3.x pandas beautifulsoup


【解决方案1】:

解决方案是将作业用括号括起来,如下所示:

for i in lst:
    
    df = pd.DataFrame()
    soup = BeautifulSoup(i)
    #print(soup)

    for link in soup.find_all('a'):
        df['links'] = [str(link.get('href'))]
        #print(link.get('href'))
        
    #get all text messages
    soup.find_all('p')
    df['messages'] = [str(soup.find_all('p'))]
    
    #get author name
    soup.find_all(class_="author--name")
    df['author'] = [str(soup.find_all(class_="author--name"))]
    
    #get username
    soup.find_all(class_= "author--username")
    df['username'] = [str(soup.find_all(class_= "author--username"))] text messages
    soup.find_all('p')
    df['messages'] = str(soup.find_all('p'))
    
    #get author name
    soup.find_all(class_="author--name")
    df['author'] = str(soup.find_all(class_="author--name"))
    
    #get username
    soup.find_all(class_= "author--username")
    df['username'] = str(soup.find_all(class_= "author--username"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2021-10-07
    • 2013-05-14
    • 2021-09-03
    • 1970-01-01
    相关资源
    最近更新 更多