我正在建立一个数据库,收集报纸网站上发布的新闻,遵循本代码的指示。。约翰·沃森·鲁尼github网站 但是,当我通过web抓取过程提取信息时,输出在括号“[]”内,我无法删除它们来清理数据并生成新闻数据框
'''
#find all the articles by using inspect element and create blank list
n=0
newslist = []
#loop through each article to find the title, subtitle, link, date and author. try and except as repeated articles from other sources have different h tags.
for item in articles:
try:
newsitem = item.find('h3', first=True)
title = newsitem.text
link = newsitem.absolute_links
subtitle = item.xpath('//a[@class="epigraph page-link"]//text()')
author = item.xpath('//span[@class="oculto"]/span//text()')
date = item.xpath('//meta[@itemprop="datePublished"]/@content')
date_scrap = dt.datetime.utcnow().strftime("%d/%b/%Y")
hour_scrap = dt.datetime.utcnow().strftime("%H:%M:%S")
print(n, '\n', title, '\n', subtitel, '\n', link, '\n', author, '\n', date, '\n', date_scrap , '\n', hour_scrap)
newsarticle = {
'title': title,
'subtitle': subtitle,
'link': link,
'autor': author,
'fecha': date,
'date_scrap': dat_scrap,
'hour_scrap': hour_scrap
}
newslist.append(newsarticle)
n+=1
except:
pass
news_db = pd.DataFrame(rows)
news_db.to_excel (r'db_article.xlsx', index = False, header=True)
news_db.head(10)
'''
我不允许嵌入图像,但打印输出如下:
在joven caso de joven que se进行的体内采购和财政调查
自杀倾向
['Una joven de 17 años Denanceóque 4
新教徒的性别政策]
{'https://www.eltiempo.com/justicia/investigacion/investigan-denuncia-de-agresion-sexual-de-policias-a-menor-en-popayan-588429'}
['这里是作者姓名]
['2021-05-14']
2021年5月15日
18:14:48
我想删除两个类型括号“[]”y“{}”,我使用了以下命令,但它们转换NAN中的值:
news_db['subtitle']= news_bd['subtitle'].str.strip(']')
news_db['subtitle']= news_bd['subtitle']..str.replace(r"\[.*\]", "")
^{} 方法返回找到的项目列表,例如
['Author']
,而不是'Author'
,就像item.find
,它在搜索多个元素(例如['Author1', 'Author2']
)时很有用。 要仅获取一个值,请使用first
参数:absoule_links
是可能aset
,您可以使用相关问题 更多 >
编程相关推荐