在列表中查找字符串

所以非常卡住


首先我的 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 = ''


温温酱
浏览 46回答 2
2回答

BIG阳

如果您有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(":")'):&nbsp; &nbsp; print(item.parent.contents[-1].strip())输出:GOOD1:56:51:56:5next_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(":")'):&nbsp; &nbsp; print(item.next_element.next_element.strip())输出:GOOD1:56:51:56:5

翻过高山走不出你

尝试使用。from bs4 import BeautifulSouphtml = """<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'):&nbsp; &nbsp; if td.find('strong'):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#Check for `strong` tag&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if td.strong.text == 'Track Rating:':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(td.find(text=True, recursive=False))&nbsp; &nbsp;#Get direct text输出:GOOD
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5