gpt4 book ai didi

python - 如何在 Django 中使用 BeautifulSoup?

转载 作者:行者123 更新时间:2023-12-05 07:19:31 25 4
gpt4 key购买 nike

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

此外,它会大大降低网站速度,这是最好的方法吗?

网页抓取代码:

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

最佳答案

即使这篇文章现在已经过时了,我的回答也可能会帮助其他人;)您必须实现线程以避免页面变慢,同时抓取过程(或任何需要时间的过程)。意味着一个任务应该总是获得一个新线程。在 YouTube 和 google 上找到多线程有很多教程,甚至专门针对 Django。祝你好运,享受编码:)

关于python - 如何在 Django 中使用 BeautifulSoup?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57745668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com