【问题标题】:Extract elements between two tags with Beautiful Soup and Python使用 Beautiful Soup 和 Python 提取两个标签之间的元素
【发布时间】:2022-01-18 05:03:21
【问题描述】:

我想爬取这个网站http://www.truellikon.ch/freizeit-kultur/anlaesse-agenda.html。 我想提取每个事件的日期和时间。 您可以看到该日期列在事件上方。为了提取日期和时间,我需要组合不同的 div,但问题是我没有用于同一日期的一组事件的“容器”。 所以我唯一能做的就是提取两个引用日期的 div 之间的所有事件。

这是提取事件信息的代码:

from bs4 import BeautifulSoup
import requests

domain = 'truellikon.ch'
url = 'http://www.truellikon.ch/freizeit-kultur/anlaesse-agenda.html'

def get_website_news_links_truellikonCh():
    
    response = requests.get(url, allow_redirects=True)
    print("Response for", url, response)

    soup = BeautifulSoup(response.content, 'html.parser')
    all_events = soup.select('div.eventItem')

    for i in all_events:
        print(i)
        print()
        input()
    
x = get_website_news_links_truellikonCh()

日期的类名是'listThumbnailMonthName' 我的问题是如何组合这些 div,如何编写选择器以便获得每个事件的确切日期和时间、标题和正文

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    您有一个父容器#tx_nezzoagenda_list,然后您必须一一阅读children

    import re
    
    from bs4 import BeautifulSoup
    import requests
    
    url = 'http://www.truellikon.ch/freizeit-kultur/anlaesse-agenda.html'
    response = requests.get(url)
    
    soup = BeautifulSoup(response.text, 'html.parser')
    container = soup.select_one('#tx_nezzoagenda_list')
    
    for child in container.children:
        if not child.name:
            continue
        if 'listThumbnailMonthName' in child.get('class'):
            base_date=child.text.strip()
        else:
            day=child.select_one('.dateDayNumber').text.strip()
            title=child.select_one('.titleText').text.strip()
            locationDate=child.select_one('.locationDateText').children
            time=list(locationDate)[-1].strip()
            time=re.sub('\s','', time)
            print(title, day, base_date, time)
    

    哪个输出

    Abendunterhaltung TV Trüllikon 10 Dezember 2021 19:00Uhr-3:00Uhr
    Christbaum-Verkauf 18 Dezember 2021 9:30Uhr-11:00Uhr
    Silvester Party 31 Dezember 2021 22:00Uhr
    Neujahrsapéro 02 Januar 2022 16:00Uhr-18:00Uhr
    Senioren-Zmittag 21 Januar 2022 12:00Uhr-15:00Uhr
    Theatergruppe "Nume Hüür", Aufführung 23 Januar 2022 13:00Uhr-16:00Uhr
    Elektroschrottsammlung 29 Januar 2022 9:00Uhr-12:00Uhr
    Senioren Z'mittag 18 Februar 2022 12:00Uhr-15:00Uhr
    Frühlingskonzert 10 April 2022 12:17Uhr
    Weinländer Musiktag 22 Mai 2022 8:00Uhr
    Auffahrtskonzert Altersheim 26 Mai 2022 10:30Uhr
    Feierabendmusik und Jubilarenehrung 01 Juli 2022 19:00Uhr
    Feierabendmusik 15 Juli 2022 12:24Uhr
    Feierabendmusik 19 August 2022 19:00Uhr
    Herbstanlass 19 November 2022 20:00Uhr
    

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多