【问题标题】:Django Web Application with beautiful soup , request带有漂亮汤的 Django Web 应用程序,请求
【发布时间】:2019-04-18 08:25:57
【问题描述】:

我希望有一个网站,当用户输入内容时,他们会在网站上获得所有抓取数据视图..

现在这个 python3 代码可以通过 jupyter notebook 正常工作。 你们可以在 jupyter notebook 中测试它。但我想要以适当的方式用于用户界面。我知道 Django 可以与 python 代码集成,但我应该把这段代码放在哪里。是models.py吗?

from urllib.request import Request, urlopen as uReq 
from bs4 import BeautifulSoup as soup

def make_soup(website) :

    req =  Request(website,headers = {'User-Agent' : 'Mozilla/5.0'})
    uClient = uReq(req)
    page_html = uClient.read()
    uClient.close()
    page_soup = soup(page_html, 'html.parser')
    return page_soup

google_news_url = 'https://www.google.com.my/search?q={}&source=Int&tbm=nws'

def forge_url (q):
    return google_news_url.format(q.replace(' ','+'))

news_url = forge_url (input('Enter Search'))
website = make_soup(news_url)
headlines = website.findAll('h3')
n = 0
for item in headlines :
    top = item.a
    #print(top)
    #print()
    text_headlines = top.text
    print(text_headlines)
    print()
    n +=1

顺便说一句,我应该在 views.py 和模板中添加什么。谢谢;)

【问题讨论】:

  • 你把它放在views.py中。

标签: python django beautifulsoup request


【解决方案1】:

抓取是一项相当耗时的任务,

获取数据需要大量时间,处理数据需要更多时间。

所以为了让一个好的网站做爬虫,你必须定义一些后台任务来完成这项工作,而用户可以做其他事情或查看进程栏。

此外,并非所有网站都是服务器端呈现的,因此您无法通过请求或类似的其他库获取页面数据。您可以使用 selenium 通过浏览器(Firefox 和 Chrome)打开页面,呈现整个页面,然后将源代码传递给 BS 等库,以便提取所需的内容。

所以我的建议是:

  • 构建一个请求页面url的视图,

  • 创建一个或多个后台任务来完成繁重的工作(以 celery 为例)

  • 然后在进程完成后将结果传递给用户。

您可以在此处找到命名库:

Selenium

Celery

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多