网络抓取事件名称、位置、价格



这是我正在抓取的网站。

我在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"})

我想把它放进一个阵列中,清洗它是非常漫长和乏味的,有没有更快的,以及如何。我用漂亮的汤从维基百科上抓取了数据,但他的网站要乏味得多。

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

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....")

最新更新