在我的项目中,我试图对用户选择的汽车进行评论。在django应用程序中,我希望将上下文字典中的数据传递给另一个scrape.py文件。代码:
models.py
class SelectCar(models.Model):
BRANDS = (
('BMW','BMW'),
('MR','Mercedes')
)
brand = models.CharField(max_length=30,
choices=BRANDS,
default="BMW")
CAR_MODELS = (
('X1','X1'),
('X2','X2'),
('X3','X3')
)
car_model = models.CharField(max_length=30,
choices=CAR_MODELS,
default="X1")forms.py
from .models import SelectCar
class SelectCarForm(forms.ModelForm):
class Meta:
model = SelectCar
fields = '__all__'scrape.py,在这里,我希望导入上下文数据,并在if- chain链中为特定的car选择url。例如,如果选择的汽车是本田惊奇,上下文应该导入到scrape.py,以便我能够选择url。
import requests
from bs4 import BeautifulSoup
"""import context here in some way"""
def happyScrape():
"""here, import the context and choose url based on chosen car
if car is Honda amaze, choose url for honda amaze and so on.
example- if brand is honda and model is amaze,
"""
url = 'https://www.carwale.com/honda-cars/amaze/user-reviews/'\
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
cw_result = requests.get(url, headers=headers)
cw_soup = BeautifulSoup(cw_result.text, 'html5lib')
scrapeList =[]
#scrape code here, stored in scrapeListHTML
for data in scrapeListHtml:
scrapeList.append(data.text)
with open(r'./scrape/scrapeListFile.txt', 'w') as f:
for item in scrapeList:
# write each item on a new line
f.write("%s\n" % item)views.py
from .forms import SelectCarForm
def ScrapeView(request):
context = {}
context['SelectCarForm'] = SelectCarForm()
if request.method == 'POST' and 'run_script' in request.POST:
from .scrape import happyScrape
happyScrape()
return render(request, "scrape.html", context)编辑通过将数据以品牌的形式传递给happyScrape()本身,car_model解决了这个问题。
发布于 2022-09-01 08:24:38
在context函数中传递来自happyScrape()的特定数据。
在scrape.py中
def happyScrape(data):
# use this data here
...在views.py中
def ScrapeView(request):
...
happyScrape(<data_from_context>)
...https://stackoverflow.com/questions/73564275
复制相似问题