【问题标题】:Get all span inside div获取div内的所有span
【发布时间】:2019-06-10 12:20:44
【问题描述】:

我正在访问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())```

【问题讨论】:

  • 您提供的网址似乎不包含您在此处发布的 html。这使您的问题不完整,并且您的问题不可重现。我的建议是使用 url 或实际的 html 来完善您的问题。 ;)
  • @sentence 代码被简化了......你知道如何在不重复的情况下获取元素内的所有元素吗?

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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    相关资源
    最近更新 更多