【问题标题】:Using BeautifulSoup to find specific text on a webpage使用 BeautifulSoup 查找网页上的特定文本
【发布时间】:2016-09-07 14:57:08
【问题描述】:

我正在尝试使用 Python 3 和 Beautiful Soup 4 从网站保存电影列表。问题是,我对 Python 和 BS 还很陌生,我真的不知道从哪里开始。

网站是http://sunsettheatre.com,电影列表就在“Past Movies:”之后。我不知道如何提取该块。我一直在谷歌上搜索,似乎 Beautiful Soup 在尝试查找标签时效果最好,但我只需要它来找到一个文本列表,它不在任何特定标签中(该网站不是经过专业设计的)。

有什么方法可以让 Beautiful Soup 和 Python 提取“过去的电影:”和“我们播放过的电影的完整列表点击这里”之间的文本?

【问题讨论】:

    标签: python html python-3.x web-scraping beautifulsoup


    【解决方案1】:

    找到元素by text,获取next font sibling并解析b标签中的事件列表,从previous sibling获取事件日期。

    完整的工作代码:

    from bs4 import BeautifulSoup
    import requests
    
    
    url = "http://sunsettheatre.com/"
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html5lib")
    
    font = soup.find("b", text="Past Movies:").find_next_sibling("font")
    for event in font.find_all("b", recursive=False):
       event_date = event.previous_sibling.strip()
       event_text = event.get_text(strip=True)
       print(event_date, event_text)
    

    打印:

    (u'January 1, 2 & 3:', u'Alvin and the Chipmunks: The Road Chip')
    (u'January 8, 9 & 10:', u"Daddy's Home")
    (u'January 15, 16 & 17:', u'Star Wars: The Force Awakens')
    (u'January 22, 23 & 24:', u'Star Wars: The Force Awakens 3D')
    (u'January 29, 30 & 31:', u'Norm of the North')
    (u'February 5, 6 & 7:', u'The Forest')
    (u'February 12, 13 & 14', u'Kung Fu Panda 3')
    (u'February 19, 20 & 21', u'Kung Fu Panda 3 3D')
    (u'February 26, 27 & 28', u'Ride Along 2')
    (u'March 4, 5 & 6', u'Deadpool')
    (u'March 11, 12 & 13', u'Gods of Egypt')
    (u'March 18, 19 & 20', u'Zootopia')
    (u'March 25, 26 & 27', u'Zootopia 3D')
    (u'April 1, 2 & 3', u'The Divergent Series: Allegiant')
    (u'April 8, 9 & 10', u'Miracles From Heaven')
    (u'April 29, 30 & May 1', u'Batman v Superman')
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      相关资源
      最近更新 更多