【问题标题】:Webscraping event name, location, price网络抓取活动名称、地点、价格
【发布时间】:2020-06-20 09:09:09
【问题描述】:

This is the website I am scraping.

我在 Jupyter 中使用 BeautifulSoup,我想知道如何从这个网站上获取活动名称、位置和价格。我在 Inspect 工具中找到了它们的位置。

现在我找到了活动名称,但我觉得我的过程很长而且没有必要。

我的计划是将所有从该页面抓取的事件数据放入一个数据框中。

import pandas as pd
import requests
import bs4
from bs4 import BeautifulSoup

kpbs_link = "https://www.kpbs.org/events/search/?unifyevents=true&vertical_events=true&base_arts=true&base_category=137/"
page = requests.get(kpbs_link)
soup = BeautifulSoup(page.text)

events = soup.find_all('h4', {"class": "list_title"})

我觉得将它放入一个数组中并清洁它非常漫长而乏味,有没有更快的方法,以及如何。我使用美丽的汤从维基百科抓取数据,但他的网站更加乏味。

【问题讨论】:

    标签: python pandas web-scraping beautifulsoup


    【解决方案1】:

    您可以尝试运行以下代码。您需要注意成本元素,因为它并不存在于所有事件中,所以我设置了一个条件来处理它。它从页面中提取事件名称、位置和价格的列表元素:

    import requests
    from bs4 import BeautifulSoup
    import pandas as pd
    name = []
    location = []
    price = []
    
    url = "https://www.kpbs.org/events/search/?unifyevents=true&vertical_events=true&base_arts=true&base_category=137"  # no trailing /
    try:
        page = requests.get(url)
    
        soup = BeautifulSoup(page.text, 'html.parser')
    
        items = soup.find_all("li", {"class": "item"})
        for item in items:
            name.append(item.find('h4', {"class": "list_title"}).text.strip())
            location.append(item.find('p', {"class": "list_place"}).text.strip())
            try:
                price.append(item.find('p', {"class": "cost"}).text.strip())
            except:
                price.append('NA')
    
        final_df = pd.DataFrame(
        {'title': name,
         'location': location,
         'price': price
        })
    except Exception as e:
        print(e)
        print("continuing....")
    

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 2016-02-06
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 2011-02-12
      相关资源
      最近更新 更多