python - 如何在 Django 中自动删除 Web Scraper 重复数据
问题描述
我在 python 中有一个网络爬虫。它将结果保存在 django 模型中,因此当我刷新页面时,它会运行 webscraper 复制已经存在的数据。我尝试使用list(dict.fromkeys (my2) )函数删除数据,但没有用。
视图.py
def Scrappy(request):
session = requests.Session()
session.headers = {
"User-Agent": 'User-Agent'}
url = 'https://www.google.com/blog/'
content = session.get(url, verify=False,).content
soup = BeautifulSoup(content, "html.parser")
obj1 = soup.find_all(
'div', {'class': 'td_module_3 td_module_wrap td-animation-stack'})
obj2 = soup.find_all(
'div', {'class': 'td_module_10 td_module_wrap td-animation-stack'})
for x in obj1:
linkX = x.find('a', {'class': 'td-image-wrap'})
#saving the fetched data into variables
link_x = linkX.get('href')
title_x = linkX.get('title')
img_src_x = x.find('img', {'class': 'entry-thumb'})['src']
link_x.replace(u"\u2019", "-")
link_x.decode('utf-16', 'ignore')
img_src_x.replace(u"\u2019", "-")
img_src_x.decode('utf-16', 'ignore')
new_Web = WebScraper()
new_Web.web_title = title_x
new_Web.web_url = str(link_x)
new_Web.my_img = str(img_src_x)
try:
my = {new_Web}
my = list(dict.fromkeys(my))
new_Web.save()
except:
pass
# new_Web.save()
for y in obj2:
linkY = y.find('a', {'class': 'td-image-wrap'})
#saving the fetched data into variables
link_y = linkY.get('href')
title_y = linkY.get('title')
img_src_y = y.find('img', {'class': 'entry-thumb'})['src']
img_src_y.replace(u"\u2019", "-")
img_src_y.decode('utf-16', 'ignore')
link_y.replace(u"\u2019", "-")
link_y.decode('utf-16', 'ignore')
new_Web2 = WebScraper()
new_Web2.web_title = title_y
new_Web2.web_url = str(link_y)
new_Web2.my_img = str(img_src_y)
try:
my2 = ["new_Web2"]
my2 = list(dict.fromkeys(my2))
new_Web2.save()
except:
pass
# new_Web2.save()
return redirect('Veb-View')
我希望不要在数据库中创建重复的项目,因为它不必要地填充数据库。请分享有关如何自动删除重复项目的方法或链接。提前致谢。
解决方案
您可以使用 get_or_create 来避免重复,例如
new_Web2,created = WebScraper.objects.get_or_create(web_title=title_y,web_url=str(link_y),my_img=str(img_src_y))
if created:
print("new object created")
else:
print("existing object retrived")
get_or_create 返回包含对象的元组和一个布尔字段,说明是否创建了新对象
推荐阅读
- javascript - Ag-Grid:一旦列超出容器大小,调整列宽并显示水平滚动条
- http - 如何使用 UnityWebRequest 在 Unity 中编写发送图像文件 (.jpg/.png) 的 HTTP 帖子?
- python - 将数据帧作为参数传递
- java - Kafka 生产者错误使用“security.protocol”
- python - sklearn:使用 PDP 功能时无法从“sklearn.utils”导入名称“_print_elapsed_time”
- javascript - 当 process.env.VARNAME 很大时,错误在 webpack 中生成 E2BIG
- javascript - Tinymce 未捕获错误:节点不能为空或未定义
- machine-learning - 请告诉我如何在决策树中拆分数字列或节点
- pool - 在 BPMN 中,如何在不弄乱整个图表的情况下将现有车道打包到新池中?
- android - 如何禁用片段中的后退按钮按下但允许片段本身实现后按逻辑