如何在Django中使用BeautifulSoup?

时间:2019-09-01 11:39:01

标签: python django beautifulsoup django-2.2

我试图在Django中创建一个网站,该网站基本上是从Google新闻中抓取数据并将其放在我的网站上。但是我不知道如何使用从Django HTML文件中从Google新闻中提取的数据。有什么办法可以做到的。

而且,它会大大减慢网站速度,这是最好的方法吗?

网络抓取代码:

from bs4 import BeautifulSoup
import requests
url = "https://news.google.com/?hl=en-IN&gl=IN&ceid=IN:en"
headers = {
    "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
n = 1
for link in soup.findAll('h3', {'class', 'ipQwMb ekueJc RD0gLb'}):
    title = link.string
    for a in link.findAll('a', {'class', 'DY5T1d'}): 
        href = a.get('href')
        link_href = href.replace(".", "")
        print("(" + str(n) + ")" + title + "\n" + "https://news.google.com" + link_href)
        n += 1

1 个答案:

答案 0 :(得分:0)

即使此帖子现在很旧,我的回答也可能会帮助其他人;) 您必须实现线程化,以避免在抓取过程(或任何需要时间的过程)的情况下降低页面速度。意味着一项任务应始终获得一个新线程。在YouTube和Google上找到多个线程,有很多教程,甚至专门针对Django。 祝您好运,并喜欢编码:)