全球时报英语新闻爬虫
生活随笔
收集整理的這篇文章主要介紹了
全球时报英语新闻爬虫
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
全球時報英語新聞爬蟲
程序說明
本程序爬取了全球時報的新聞
本程序是由于上某課需要英文數據學習使用所以爬取了全球時報數據作為用例
禁止轉載,禁止非學習外其它用途
使用方法
使用方法
安裝python3
安裝所需庫 pip install -r requirements.txt
程序使用selenium模擬Edge進行爬取 請配置好Edge的webdriver
點此查看Edge的WebDriver
Anaconda用戶通常在Anaconda/envs里能找到你對應的虛擬環境
下載配置到python文件夾并修改包內的 webdriver.py 文件
WebDriver配置通常在你的Python目錄下的Lib\site-packages\selenium\webdriver\下,我們這里是Edge的
配好后現在就可以使用了
可以用下面代碼測試一下是否能調出瀏覽器,查看網頁是否正常
其他瀏覽器操作類似,修改WebDriver的類型即可
程序
Python3(我是用Python3.8.11)
所需庫
可粘到目錄下保存為requirements.txt,使用pip install -r requirements.txt安裝完
#!/usr/bin/python # -*- coding:utf-8 -*-import xlrd import xlwt import time import logging import xlutils.copy from time import sleep from lxml import etree from selenium import webdriverlogging.basicConfig(level = logging.DEBUG) class crawler:''' 環球時報新聞爬取類類實現了爬取環球時報各個欄目下的一定數量的文章并將其存入excel文件中Auther: GyAttributes: url : 爬取的頁面的urlcolumn_dict : 爬取欄目字典(中文目前未使用)excel_file_name : 保存文檔名crawl_page_num : 爬取欄目頁面的幾頁(模擬用戶點擊MORE)deiver_wait_time : 隱式等待(瀏覽器加載項目最長等待時間)passage_wait_time : 進入頁面后等待多久'''def __init__(self, url, column_dict, excel_file_name, excel_sheet_name, crawl_page_num = 10, deiver_wait_time = 10, page_wait_time = 1):''' 初始化 '''self.url = urlself.column_dict = column_dictself.excel_file_name = '{}_{}_crawl_by_gy.xls'.format(excel_file_name, time.strftime("%Y-%m-%d", time.localtime()))self.excel_sheet_name = excel_sheet_nameself.excel_sheet_title = ['標題', '欄目', '作者', '發布時間', '鏈接', '內容']self.crawl_page_num = crawl_page_numself.page_wait_time = page_wait_timeself.browser = webdriver.Edge()self.browser.implicitly_wait(deiver_wait_time)def crawl(self):'''開始爬取'''logging.info('建表并寫入表頭')workbook = xlwt.Workbook(encoding = 'utf-8')worksheet = workbook.add_sheet(self.excel_sheet_name)for si, i in enumerate(self.excel_sheet_title):worksheet.write(0, si, i)workbook.save(self.excel_file_name)logging.info('開始爬取')for column, column_name in self.column_dict.items():logging.info('爬取欄目 {}'.format(column))self.process_a_column(column)self.browser.quit()logging.info('爬取完成')def process_a_column(self, column):'''爬取一個欄目Args:column : 欄目名'''self.browser.get('{}/{}'.format(self.url, column))sleep(self.page_wait_time)for times in range(self.crawl_page_num):#點擊MORE展開一頁self.browser.find_element_by_class_name('show_more').click()sleep(self.page_wait_time)source = self.browser.page_sourcelogging.info('開始解析欄目 {}'.format(column))try:html_tree = etree.HTML(source)passage_list = self.process_column_link(html_tree)except Exception as e:logging.error('解析欄目 {} 鏈接失敗,錯誤信息: {}'.format(column, e))logging.info('欄目 {} 解析完成'.format(column))try:for title, link in passage_list:self.process_a_passage(title, link, column)except Exception as e:logging.error('處理文章失敗,錯誤信息: {}'.format(e))def process_column_link(self, html_tree):'''處理頁面獲取所有文章標題和連接Args:html : 欄目的樹結構Returns:一個文章標題和鏈接元組構成的列表'''ret_list = []passages_list = html_tree.xpath('//div[@class="level01_list"]//div[@class="list_info"]/a')if passages_list:for passage in passages_list:title = passage.xpath('./text()')[0]link = passage.xpath('./@href')[0]logging.debug('獲取到當前文章 {} , url {}'.format(title, link))ret_list.append((title, link))return ret_listdef process_a_passage(self, title, link, column):'''處理文章信息Args:title : 文章標題link : 鏈接column : 欄目'''logging.info('正在處理文章 {} 鏈接 {}'.format(title, link))row = []self.browser.get(link)sleep(self.page_wait_time)source = self.browser.page_sourcehtml_tree = etree.HTML(source)content_lst = html_tree.xpath('//div[@class="article_page"]//div[@class="article"]//div[@class="article_content"]//div[@class="article_right"]/br')#找不到文章內容直接退出if not content_lst:return#獲取文章內容content = ''for one_content in content_lst:if one_content.tail:content = content + '\n' + one_content.tail.strip()author_and_publictime_span = html_tree.xpath('//div[@class="article_page"]//div[@class="article"]//div[@class="article_top"]//div[@class="author_share"]//div[@class="author_share_left"]/span')#獲取作者auther = author_and_publictime_span[0].text.replace('By ', '')#獲取發表時間public_time = author_and_publictime_span[1].text.replace('Published: ', '')row.append(title)row.append(column)row.append(auther)row.append(public_time)row.append(link)row.append(content)self.write_excel(row)logging.debug('爬取一條信息 : {} {} {} {} {} {}'.format(title,column, auther, public_time, link, content))logging.info('文章 {} 處理完成'.format(title))def write_excel(self, row):'''寫入文章信息Args:row : 處理完寫入一行的內容'''try:book = xlrd.open_workbook(self.excel_file_name, formatting_info=True) # 讀取Excelcopy_book = xlutils.copy.copy(book)copy_sheet = copy_book.get_sheet(self.excel_sheet_name)rowns = len(copy_sheet.rows)for si, i in enumerate(row):copy_sheet.write(rowns, si, i)copy_book.save(self.excel_file_name)except Exception as e:logging.error('讀取文件失敗,錯誤信息: {}'.format(e))if __name__ == '__main__':news_columns_dict = {'politics' : '政治','society' : '社會','diplomacy' : '外交','military' : '軍事','science' : '科學','odd' : '奇文','graphic' : '圖文','100-CPC-Stories-in-100-Days' : '100天100個CPC故事'}globaltimes_crawler = crawler('https://www.globaltimes.cn/china', news_columns_dict, 'globaltimes_news', 'globaltimes', 10)globaltimes_crawler.crawl()結果如下
謝謝使用
總結
以上是生活随笔為你收集整理的全球时报英语新闻爬虫的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android-Animations的使
- 下一篇: Portable项目类型之前多个目标类型