【问题标题】:BeautifulSoup Python Extracting Tag Title For Specific Tags With AttributeBeautifulSoup Python为具有属性的特定标签提取标签标题
【发布时间】:2020-05-02 14:27:01
【问题描述】:

我正在使用 beautifulsoup 制作一个刮板,用于为 Songkick 上的某些艺术家提取音乐会信息。我正在使用的网址是https://www.songkick.com/metro-areas/17835-us-los-angeles-la/february-2020?page=1。我已经能够提取所有艺术家、场地、城市和州信息,我唯一遇到的问题是提取音乐会的日期。

在查看 html 元素时,我看到节目的日期被列为 li title="Saturday 01 February 2020" 值,例如 ul class="event-listings" 下的孩子。我尝试执行的一种方法是提取 li 标题下的时间日期时间值,但我的输出包括每个 li 时间日期时间的整个 html 标记,而不仅仅是日期时间。我正在寻找提取 li 标题或时间日期时间值。这些 li 也没有类。

这是我的一些代码

import requests
from bs4 import BeautifulSoup as bs4

pages=[]
artists=[]
venues=[]
dates=[]
cities=[]
states=[]

pages_to_scrape=1

for i in range(1, pages_to_scrape+1):
    url = 'https://www.songkick.com/metro-areas/17835-us-los-angeles-la/february-2020?page={}'.format(i)
    pages.append(url)
for item in pages:
    page = requests.get(item)
    soup = bs4(page.text, 'html.parser')
    for m in soup.findAll('li', title=True):
        date = m.find('time')
        print(date)

输出:

<time datetime="2020-02-01T20:00:00-0800"></time>
<time datetime="2020-02-01T20:00:00-0800"></time>
<time datetime="2020-02-01T19:00:00-0800"></time>
<time datetime="2020-02-01T19:00:00-0800"></time>
<time datetime="2020-02-01T21:00:00-0800"></time>
etc...

寻找这样的输出:

2020-02-01
2020-02-01
2020-02-01
etc...

或者如果能够获取 li 的标题值,输出如下:

Saturday 01 February 2020
Saturday 01 February 2020
Saturday 01 February 2020
Saturday 01 February 2020
etc...

我很好奇我是否能够在日期时间的 " 处拆分,但由于它不是文本,我认为这是不可能的。另外,我不想抓住第一个 li class= " with-date”,因为这只是页面日期的标题,说明为什么我不只是抓住所有的 li。

【问题讨论】:

    标签: python html datetime beautifulsoup attributes


    【解决方案1】:

    尝试m.find('time')['datetime'] 而不是m.find('time')

    【讨论】:

      【解决方案2】:

      这是实现此目的的一种方法:

      import requests
      from bs4 import BeautifulSoup
      page = requests.get("https://www.songkick.com/metro-areas/17835-us-los-angeles-la/february-2020?page=1")
      soup = BeautifulSoup(p.content, "html.parser")
      tags = soup.find_all("time")
      [t["datetime"].split("T")[0] for t in tags]
      

      注意事项:

      1. 我很确定以这种方式抓取 Songkick 违反了他们的条款和条件。
      2. 您可以考虑使用他们的 API,效果很好:https://www.songkick.com/developer

      【讨论】:

      • 谢谢你,我一定会检查 API。我申请了 API 密钥,正在等待回复。感谢支持!
      猜你喜欢
      • 2013-07-01
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      相关资源
      最近更新 更多