我正在使用BeautifulGroup对表元素进行更改。更具体地说,我向tbody和td元素添加了一个类。这很好用,但只适用于第一个匹配元素。我不知道如何迭代页面上的其余匹配元素。在soup = BeautifulSoup(combine_html, "html.parser")
soup.find('tbody')['class'] = 'list'
soup.find('td')['class'] = 'fuzzy'
soup
发生以下变化
^{pr2}$
~~~更新~~~
我没有得到任何输入,所以可能我的问题没有贴上正确的标签,或者答案很简单,所以没有人发布。在
我可以让它工作-但它真的很难看。参见以下代码:import csv
import pandas as pd
# import numpy as np
from bs4 import BeautifulSoup, Tag, NavigableString
# Select columns from csv file
csv_columns = ['Email', 'Recipient Name', 'Department', 'Clicked Link?']
# Set input csv file to read from nd specify columns using csv_columns variable
df = pd.read_csv('camp1_beneficiary_fullcsv.csv', skipinitialspace=True, usecols=csv_columns)
# Set the HTML header
# Set Bootstrap CSS
# Set CSS location for list.min.js Javascript - mainly the list class
# Set div id for list.min.js
html_header="""
Sort by name
"""
# Set HTML 'footer'
# Specify list.min.js external javascript file and code
html_footer ="""
var options = {
valueNames: [ 'fuzzy' ]
};
var userList = new List('users', options);
"""
# Generate HTML body using df.to_html from Pandas
html_body = df.to_html(classes=["table-bordered", "table-striped", "table-hover"])
# Combine html header, body, and footer into variable
combine_html = (html_header + html_body + html_footer)
# Find elements in HTML and add classes to support javascript classes for filtering
soup = BeautifulSoup(combine_html, "html.parser")
soup.find('tbody')['class'] = 'list'
soup
f = open('test.html','w')
f.write(str(soup))
f.close()
f = open('test.html', 'r')
filedata = f.read()
f.close()
newdata = filedata.replace("
", "")f = open('final.html', 'w')
f.write(newdata)
f.close()