Python 3.x 试图使for循环在命中html表中的某一行时中断

Python 3.x 试图使for循环在命中html表中的某一行时中断,python-3.x,selenium,beautifulsoup,Python 3.x,Selenium,Beautifulsoup,我正试图从下面代码中找到的wesbite中刮取一个webtable。基本上,我只尝试刮今天的游戏,当我的for循环碰到HTML表中包含第二天游戏信息的部分时停止。我试过用谷歌搜索这个问题,但似乎还是解决不了。任何帮助都将不胜感激。我的代码贴在下面 url='http://www.oddsportal.com/baseball/usa/mlb/' driver = webdriver.Chrome() driver.get(url) time.sleep(5) driver.find_elem

我正试图从下面代码中找到的wesbite中刮取一个webtable。基本上,我只尝试刮今天的游戏,当我的for循环碰到HTML表中包含第二天游戏信息的部分时停止。我试过用谷歌搜索这个问题,但似乎还是解决不了。任何帮助都将不胜感激。我的代码贴在下面

url='http://www.oddsportal.com/baseball/usa/mlb/'
driver = webdriver.Chrome() 
driver.get(url)
time.sleep(5)

driver.find_element_by_id('user-header-timezone-expander').click() #get to est timezone
time.sleep(2)
driver.find_element_by_xpath("//*[contains(text(), 'GMT - 4')]").click() #get to est timezone
time.sleep(2)

content=driver.page_source

soup=BeautifulSoup(content,'lxml')


file_dates = []
todays_games=soup.find('table',{'class':'table-main'})
dummy_row=soup.find_all(attrs={'class':'table-dummyrow'})

for games in todays_games.select('td.table-time.datet'): #gets the time of the game
    games= [games.text]
    file_dates.append(games)

    if dummy_row==dummy_row[1]: #I want the for loop to break when it hits the gray header titled "Tomorrow, 22 Jul" on the webpage
        break

print(file_dates)  #still returns every game on the website though

要获取今天的比赛时间,您可以尝试以下代码:

games = [td.text for td in driver.find_elements_by_xpath('//table[@id="tournamentTable"]//td[contains(@class, "datet") '
                                                     'and following::span[starts-with(., "Tomorrow,")]]')]
print(games)
如果仍要使用bs4,请尝试:

file_dates = []
todays_games=soup.find('table',{'class':'table-main'})

for games in todays_games.select('tr')[2:]:
    if games.select('td.datet'):
        file_dates.append(games.select('td.datet')[0].text)
    if games.select('th'):
        break

非常感谢您的回答,您能让我了解一下您提供的这个xpath吗?xpath将返回DOM中以子字符串开始的跨度之前出现的
“tournamentTable”
中所有具有类名
“datet”
的单元格,但是,除了使用Xpath之外,您还有其他解决方案吗?你的答案很好,但我希望有一个解决方案,当它出现在灰色日期行时,我可以打破循环,就像我在代码中尝试的那样。我真的很想看看这会是什么样子,我似乎无法用这种方式解决它!我甚至不能尝试,因为目前你太棒了,谢谢。我想我需要开始练习我的XPath了!哈哈