【发布时间】:2021-12-15 03:12:05
【问题描述】:
我正在使用 fastAPI 创建自己的爬虫 API。我遇到的问题是我似乎做错了什么,因为我的数据(抓取的数据)没有显示在浏览器上。我已经将我的爬虫变成了一个类,以便在我的 FastAPI 应用程序中使用它,并且数据显示在我的控制台上,而不是通过浏览器显示在 uvicorn 服务器上。我配置正确。我也附上了浏览器截图。
爬虫 API
from fastapi import FastAPI
from Scraper import scrape
app = FastAPI()
data = scrape()
@app.get("/data")
async def songs():
return data.scrapedata()
刮板
import time
from selenium import webdriver
import selenium
from selenium.webdriver.chrome import service
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
import pandas as pd
class scrape:
def scrapedata(self):
ser = Service("C:\Program Files (x86)\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(options=options,service=ser)
driver.get('https://soundcloud.com/jujubucks')
print(driver.title)
wait = WebDriverWait(driver,30)
wait.until(EC.element_to_be_clickable((By.ID,"onetrust-accept-btn-handler"))).click()
song_list = []
for i in range(1, 35):
song_contents = driver.find_element(By.XPATH, "//li[@class='soundList__item'][{}]".format(i))
driver.execute_script("arguments[0].scrollIntoView(true);",song_contents)
try:
search = song_contents.find_element(By.XPATH, ".//a[contains(@class,'soundTitle__username')]/span").text
search_song = song_contents.find_element(By.XPATH, ".//a[contains(@class,'soundTitle__title')]/span").text
search_date = song_contents.find_element(By.XPATH, ".//time[contains(@class,'relativeTime')]/span").text
search_plays = song_contents.find_element(By.XPATH, ".//span[contains(@class,'sc-ministats-small')]/span").text
except NoSuchElementException:
continue
if search_plays == False:
continue
option ={
'Artist': search,
'Song_title': search_song,
'Date': search_date,
'Streams': search_plays
}
song_list.append(option)
df = pd.DataFrame(song_list)
print(df)
driver.quit()
data = scrape()
data.scrapedata()
【问题讨论】:
-
它应该返回一些东西,
scrapedata函数中没有返回 -
能否请您澄清一下,我有点困惑。你的意思是没有东西可以退货?
-
scrapedata 函数应该实际返回什么,将它传递给一个变量和
return它 -
我认为最好是你为我做榜样,因为我迷路了。
-
添加了解释作为答案,看看吧!
标签: python selenium selenium-webdriver web-scraping fastapi