为了账号安全,请及时绑定邮箱和手机立即绑定

在列表中查找字符串

在列表中查找字符串

温温酱 2024-01-22 14:59:27
所以非常卡住首先我的 HTML 很难。有时它会丢失数据,如下所示。我的目的是在强之后获取文本(很好,1:56:5,1:56.5 等等)。由于数据很混乱,我可能需要嵌套的 if 语句,因此当我构造列表时,我的数据是 true (参见下面的代码)缺少数据 HTML<td><strong>Track Rating:</strong> GOOD</td><td></td><td><strong>Gross Time:</strong> 1:56:5</td><td><strong>Mile Rate:</strong> 1:56:5</td>普通 HTML<td><strong>Track Rating:</strong> GOOD</td><td><strong>Gross Time:</strong> 2:29:6</td><td><strong>Mile Rate:</strong> 1:58:6</td><td><strong>Lead Time:</strong> 30.3</td>我的代码在下面,我想从 if 语句中提取数据,但我卡住了。任何帮助表示赞赏。我想做的是在这里收集 GOOD 并将其存储在 track rating 中,并对我抓取的每个跟踪评级执行此操作- 如果它不存在,我想将其存储为空白。tableoftimes = race.find('table', class_='raceTimes')                for row in tableoftimes.find_all('tr'):                    string23 = [td.get_text() for td in row.find_all('td')]                    matching = [s for s in string23 if "Track Rating: " in s]                    if matching:                        trackrating = matching (#want to split to get after : but wont work in list)                    else:                        trackrating = ''
查看完整描述

2 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

如果您有BS4 4.7.1或更高版本,您可以尝试以下代码。


尝试以下CSS选择器,它将识别td标签下的所有强标签conatins : ,然后获取父标签td,然后用于contents[-1]获取值


代码:


html='''<td><strong>Track Rating:</strong> GOOD</td>

<td></td>

<td><strong>Gross Time:</strong> 1:56:5</td>

<td><strong>Mile Rate:</strong> 1:56:5</td>'''


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


for item in soup.select('td>strong:contains(":")'):

    print(item.parent.contents[-1].strip())

输出:


GOOD

1:56:5

1:56:5

next_element或者,您也可以在找到强标签后使用。第next_element一个是强标签,第二个next_element打印强标签后的值


html='''<td><strong>Track Rating:</strong> GOOD</td>

<td></td>

<td><strong>Gross Time:</strong> 1:56:5</td>

<td><strong>Mile Rate:</strong> 1:56:5</td>'''


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


for item in soup.select('td>strong:contains(":")'):

    print(item.next_element.next_element.strip())

输出:


GOOD

1:56:5

1:56:5


查看完整回答
反对 回复 2024-01-22
?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

尝试使用。


from bs4 import BeautifulSoup


html = """<td><strong>Track Rating:</strong> GOOD</td>

<td></td>

<td><strong>Gross Time:</strong> 1:56:5</td>

<td><strong>Mile Rate:</strong> 1:56:5</td>"""


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

for td in soup.find_all('td'):

    if td.find('strong'):         #Check for `strong` tag 

        if td.strong.text == 'Track Rating:':

            print(td.find(text=True, recursive=False))   #Get direct text

输出:


GOOD


查看完整回答
反对 回复 2024-01-22
  • 2 回答
  • 0 关注
  • 38 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信