【发布时间】:2020-07-20 16:38:53
【问题描述】:
这是目标网站:https://www.mobihealthnews.com/news?page=0
我创建了一个 python 函数来从新闻页面中抓取所有信息并将所有内容存储在 pandas 数据框中,如下所示:
def scrape_global_news(url):
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
frame=[]
filename="global_mobi_health_news.xlxs"
f=open(filename,"w", encoding = 'utf-8')
for row in soup.select('.group-left .views-row'):
Region = "Global"
Title = row.select_one('.views-field-title').get_text(strip=True)
Content = row.select_one('.views-field-body').get_text(strip=True)
Link = 'https://www.mobihealthnews.com' + row.a['href']
Date = row.select_one('.day_list').get_text(strip=True)
Author = row.select_one('.author_list').get_text(strip=True)
frame.append((Region,Title,Content,Date,Link,Author))
f.write(Title.replace(",","^")+","+Link+","+Author.replace(",","^")+","+Content.replace(",","^")+","+Date.replace(",","^")+"\n")
f.close()
df_global=pd.DataFrame(frame, columns=['Region','Title','Summarized Content','Creation Date','Source','Author Name'])
return df_global
scrape_global_news('https://www.mobihealthnews.com/news?page=0')
下图是最终结果:
现在,我遇到了两个主要问题:
-
添加并实现一项功能以检查上面的网页内是否有新文章(即
df_global.Title[0] =! Title ],如果此条件为真,则在第一个数据帧中添加具有函数scrape_global_news的新文章行。 -
使此脚本每 24 小时自动运行一次,并将其部署在云服务提供商 (?) 中。关于这一点,我不太确定是否需要适当的云服务。
感谢您的宝贵时间。
编辑:为了更好地解释 #1 问题:
当我昨天(2020 年 7 月 21 日)发布问题时,第一行是上面链接的网站中的最新文章(即最新文章)。如果您今天查看网站,顶部还有 4 篇品牌新闻文章(这个数字很可能每天都在增加)。我想从网站内的 4 篇新文章中获取信息(使用“scrape_global_news”功能)并将它们存储在数据框的顶部。最终的范围是从最近的文章到最近的文章排序
【问题讨论】:
-
不存储在本地,而是写入数据库
-
@bigbounty 谢谢。你能详细说明一下你的答案吗? “到数据库”是什么意思?
-
好的,我会写一个答案,这样更好。提醒一下,插入到 mysql 之类的数据库中,数据将被持久化
-
@bigbounty 谢谢,我还在想办法用python不断更新df(即在网站内推送新文章时将新行添加到顶部)
-
您可以使用谷歌云平台cloudsql。 GCP 提供一年免费 300 美元
标签: python-3.x web-scraping beautifulsoup