python - 如何解析 HTML 表格,其行在 <tr> 标签下同时包含 <th> 和 <td> 标签?

标签 python html web-scraping beautifulsoup

我似乎找不到这个问题的答案,所以我很困惑。我正在使用 Beautifulsoup 和以行标签 <th> 开头的表格解析 HTML 表格。然后是数据<td> 。我正在解析数据,然后将其写入 CSV 文件,但我在包含以 <th> 开头的每行的“行标题”时遇到问题。标签。

这是我到目前为止所得到的,它完成了除了 <th> 之外的大部分工作。行标签 <th> :

headers = [header.text.strip() for header in table.find_all('th',{'scope' :'col'})]

rows = []

for row in table.find_all('tr'):
    rows.append([val.text.encode('utf8').rstrip() for val in row.find_all('td')])
with open('filename.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(headers)
    writer.writerows(row for row in rows if row)

有没有办法将其附加到rows还有?非常感谢任何帮助。

最佳答案

BeautifulSoup find_all 函数可以获取一个列表,因此要获取第th,您可以按如下方式修改脚本:

headers = [header.text.strip() for header in table.find_all('th',{'scope' :'col'})]
rows = []

for row in table.find_all('tr'):
    rows.append([val.text.encode('utf8').rstrip() for val in row.find_all(['td', 'th'])])

with open('filename.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(headers)
    writer.writerows(row for row in rows if row)

关于python - 如何解析 HTML 表格,其行在 <tr> 标签下同时包含 <th> 和 <td> 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33888369/

相关文章:

python - 将字符串与字符列表进行比较

javascript - 外部 jQuery 文件似乎没有执行

html - 如何设置多选的宽度?

excel - 使用 VBA 在 span 标签内的 <p> 元素内获取文本

Python网页抓取数据请求错误

python - pandas : pd. concat 导致重复的列

python - 如何在 Pandas 中创建新列,并有条件重复另一列的值?

python - 在 for 循环中重复使用相同的变量名两次

html - 如何在我的 FlexSlider 中添加内容?

python - 没有 BS4 python 类的刮表