【发布时间】:2020-01-22 19:50:54
【问题描述】:
所以我试图抓取一个网站of its staff roster,我希望最终产品是{staff: position} 格式的字典。我目前坚持将每个员工姓名和职位作为单独的字符串返回。很难清楚地发布输出,但它本质上是在名称列表中,然后是位置。例如,列表中的第一个名字将与第一个位置配对,依此类推。我已经确定每个名字和职位都是class 'bs4.element.Tag。我相信我需要获取名称和位置并列出每个列表,然后使用zip 将元素放入字典中。我已经尝试实现这一点,但到目前为止没有任何效果。通过使用class_ 参数,我可以得到我需要的最低文本是div 包含在其中的个人p。我仍然对python 缺乏经验并且对网络抓取不熟悉,但我精通相对论使用 html 和 css,非常感谢您的帮助。
# Simple script attempting to scrape
# the staff roster off of the
# Greenville Drive website
import requests
from bs4 import BeautifulSoup
URL = 'https://www.milb.com/greenville/ballpark/frontoffice'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
staff = soup.find_all('div', class_='l-grid__col l-grid__col--xs-12 l-grid__col--sm-4 l-grid__col--md-3 l-grid__col--lg-3 l-grid__col--xl-3')
for staff in staff:
data = staff.find('p')
if data:
print(data.text.strip())
position = soup.find_all('div', class_='l-grid__col l-grid__col--xs-12 l-grid__col--sm-4 l-grid__col--md-6 l-grid__col--lg-6 l-grid__col--xl-6')
for position in position:
data = position.find('p')
if data:
print(data.text.strip())
# This code so far provides the needed data, but need it in a dict()
【问题讨论】:
标签: python-3.x dictionary web-scraping beautifulsoup python-requests