获取所有div内的跨度

时间:2019-06-10 12:20:44

标签: python-3.x beautifulsoup selenium-chromedriver

我正在访问https://footystats.org/页,因为我需要从中获取一些信息。 HTML代码如下所示

<span class="timezone-convert-match-regular">07:00pm</span>
<span class="timezone-convert-match-regular">08:00pm</span>
</div>
 <div class="league-data"> Nigeria A
<span class="timezone-convert-match-regular">07:15pm</span>
<span class="timezone-convert-match-regular">08:30pm</span>
</div>

我需要显示如下

Internacional Friendless 07:00pm
Internacional Friendless 08:00pm
Nigeria A 07:15pm
Nigeria A 08:30pm

我的代码python

html = driver.page_source
soup = BeautifulSoup(html, "lxml")
for liga, hour in zip( soup.select('div.league-data'), soup.find_all('span', attrs={'class': 'timezone-convert-match-regular'}) ):
    print(liga.text.strip(),hour.text.strip())```

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码:

from bs4 import BeautifulSoup

data = '''
 <div class="league-data"> Internacional Friendless
 <span class="timezone-convert-match-regular">07:00pm</span>
<span class="timezone-convert-match-regular">08:00pm</span>
</div>
 <div class="league-data"> Nigeria A
<span class="timezone-convert-match-regular">07:15pm</span>
<span class="timezone-convert-match-regular">08:30pm</span>
</div>'''

soup = BeautifulSoup(data, 'lxml')

l = [(div.contents[0].strip(), span.text.strip())
    for div in soup.select('div.league-data')
    for span in div.select('span')]

for match, hour in l:
    print(match, hour)

打印:

Internacional Friendless 07:00pm
Internacional Friendless 08:00pm
Nigeria A 07:15pm
Nigeria A 08:30pm