未分类

爬虫目标指定日期,爬取人民日报所有版面的新闻简要分析版面链接分析发现一共有20个版面,分别有20个链接,只是每个链接后的数字不同http://paper.people.com.cn/rmrb/html/2020-03/12/nbs.D110000renmrb_01.htm爬虫结构用到模块:requests、BeautifulSoup、gevent构造参数类需要下载其他日期,自行修改就好classTOOL():#年月yyyy-mm格式date="2020-03"#日期day="12"#新闻详情页text_url="http://paper.people.com.cn/rmrb/html/{}/{}/".format(date,day)#版面URL列表@classmethoddefget_urls(cls):urls=list()#链接列表fornuminrange(1,20):#10以下数字补0if1<=num<10:num="0"+str(num)urls.append("http://paper.people.com.cn/rmrb/html/{}/{}/nbs.D110000renmrb_{}.htm".format(cls.date,cls.day,num))returnurls获取新闻页链接获取一个版面的新闻链接defget_layout_url(url):"""返回值:[{"layout":layout,"href":href},{"layout":layout,"href":href},...]"""print(url)r=requests.get(url=url)r.encoding=r.apparent_encoding#解析网页获取版面名称、文章链接soup=BeautifulSoup(r.text,"html.parser")list_l_soup=soup.find(name="div",attrs={"class":"list_l"})#获取版面名layout=list_l_soup.find_next(name="div",attrs={"class":"l_t"}).string.strip()print(layout)ul_soup=list_l_soup.find_next(name="div",attrs={"id":"titleList"}).find_next(name="ul")li_soup=ul_soup.find_all(name="li")#返回值列表href_titles=list()forhref_title_taginli_soup:#获取hrefhref=TOOL.text_url+href_title_tag.find(name="a")["href"]print(href)#结果组合href_titles.append({"layout":layout,"href":href})returnhref_titles下载新闻并保存提前创建好rb/目录defdownload(href_titles):forhref_titleinhref_titles:#获取新闻页r=requests.get(url=href_title.get("href"))r.encoding=r.apparent_encoding#解析新闻页soup=BeautifulSoup(r.text,"html.parser")soup_text=soup.find(name="div",attrs={"class":"text_c"})#文章标题title=soup_text.h1.stringprint(title)#正文main_sc=soup_text.find_next(name="div",attrs={"id":"ozoom"})#正文里有一段script的注释,对结果有影响,需要替换掉main_sc.find_next(name="script",attrs={"language":"javascript"}).string=""main_text=main_sc.get_text().strip()#写入文件withopen("rb/"+title+".txt","w+",encoding="utf-8")asfile:file.write(main_text)主逻辑if__name__=='__main__':#通过for循环获取所有新闻链接,组成列表href_titles=[get_layout_url(url)forurlinTOOL.get_urls()]#添加协程队列并下载layout_url_list=[gevent.spawn(download,href_title)forhref_titleinhref_titles]gevent.joinall(layout_url_list)