【发布时间】:2021-09-05 18:43:55
【问题描述】:
我正在做一个网络抓取任务,我已经可以用非常基本的方式收集数据了。
基本上,我需要一个函数来从 Allmusic.com 收集歌曲和艺术家的列表,然后将数据添加到 df 中。在这个例子中,我使用这个链接:https://www.allmusic.com/mood/tender-xa0000001119/songs
到目前为止,我设法完成了大部分目标,但是,我必须执行两个不同的函数(def get_song() 和 def get_performer())。
如果可能的话,我想要一个替代方案来加入这两个功能。
使用的代码如下:
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0'}
link = "https://www.allmusic.com/mood/tender-xa0000001119/songs"
# Function to collect songs (title)
songs = []
def get_song():
url = link
source_code = requests.get(url, headers=headers)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for td in soup.findAll('td', {'class': 'title'}):
for a in td.findAll('a')[0]:
song = a.string
songs.append(song)
# Function to collect performers
performers = []
def get_performer():
url = link
source_code = requests.get(url, headers=headers)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for td in soup.findAll('td', {'class': 'performer'}):
for a in td.findAll('a'):
performer = a.string
performers.append(performer)
get_song(), get_performer() # Here, I call the two functions, but the goal, if possible, is to use one function.
df = pd.DataFrame(list(zip(songs,performers)), columns=['song', 'performer']) # df creation
【问题讨论】:
-
您可以将两个函数包装在另一个调用它们的函数中。例如,
get_data。在特定情况下,虽然利益有限...... -
这能回答你的问题吗? Call a function with argument list in python
标签: python pandas web-scraping beautifulsoup