【问题标题】:How to use if statments on Tags in Beautiful Soup?如何在 Beautifulsoup 中的标签上使用 if 语句?
【发布时间】:2019-03-22 02:44:24
【问题描述】:

我是一个使用 Beautiful Soup 的初学者,我有一个关于“if”语句的问题。

我正在尝试从网页中的表格中提取数据,但也有处理表格和后期表格。

所有需要的表格都有表格的分区,而无用的表格有各种分区。

我想做的是使用 find_all 搜索所有表分区,然后循环遍历结果并将 .contents 方法的第一项是具有属性 align = ' 的标签的所有分区附加到列表中center',但我不知道如何使用标签作为 Beautiful Soup 对象并且不知道如何使用它。

下面有我尝试过的代码,如果有人能给我一些提示,将不胜感激。

import requests
from bs4 import BeautifulSoup

r = requests.get('https://afltables.com/afl/stats/2018.html')

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

results = soup.find_all('tr')

lists =[]
for result in results:
    if result.contents[0] == 'align = centre':
        #append to some list

【问题讨论】:

  • 你的意思是results = soup.select('td[align=center]')

标签: python html web-scraping html-table beautifulsoup


【解决方案1】:

我相信这会让你得到你想要的。

for result in results:
    if 'align="center"' in str(result.contents[0]):
        #append to some list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 2013-11-01
    相关资源
    最近更新 更多