python 뉴스 포털 사이트의 예시

프로젝트 주소:


https://github.com/Python3Spiders/AllNewsSpider

어떻게 사용합니까


모든 폴더 아래의 코드는 플랫폼에 대응하는 뉴스 파충류이다
  • py 파일을 직접 실행합니다
  • pyd 파일이 필요합니다. pengpai_로 가정하십시오.news_spider.pyd
  • pyd 파일을 로컬로 다운로드하고 새 프로젝트를 만들고pyd 파일을 넣습니다
    프로젝트 루트 디렉터리에 새 runner를 만듭니다.py, 아래 코드를 쓰면 실행 및 캡처
    
    import pengpai_news_spider
    pengpai_news_spider.main()

    예제 코드


    바이두 뉴스
    
    # -*- coding: utf-8 -*-
    #          , 
    
    import requests
    
    from datetime import datetime, timedelta
    
    from lxml import etree
    
    import csv
    
    import os
    
    from time import sleep
    from random import randint
    
    
    def parseTime(unformatedTime):
        if ' ' in unformatedTime:
            minute = unformatedTime[:unformatedTime.find(' ')]
            minute = timedelta(minutes=int(minute))
            return (datetime.now() -
                    minute).strftime('%Y-%m-%d %H:%M')
        elif ' ' in unformatedTime:
            hour = unformatedTime[:unformatedTime.find(' ')]
            hour = timedelta(hours=int(hour))
            return (datetime.now() -
                    hour).strftime('%Y-%m-%d %H:%M')
        else:
            return unformatedTime
    
    
    def dealHtml(html):
        results = html.xpath('//div[@class="result-op c-container xpath-log new-pmd"]')
    
        saveData = []
    
        for result in results:
            title = result.xpath('.//h3/a')[0]
            title = title.xpath('string(.)').strip()
    
            summary = result.xpath('.//span[@class="c-font-normal c-color-text"]')[0]
            summary = summary.xpath('string(.)').strip()
    
            # ./  ,.//  / 
            infos = result.xpath('.//div[@class="news-source"]')[0]
            source, dateTime = infos.xpath(".//span[last()-1]/text()")[0], \
                               infos.xpath(".//span[last()]/text()")[0]
    
            dateTime = parseTime(dateTime)
    
            print(' ', title)
            print(' ', source)
            print(' ', dateTime)
            print(' ', summary)
            print('
    ') saveData.append({ 'title': title, 'source': source, 'time': dateTime, 'summary': summary }) with open(fileName, 'a+', encoding='utf-8-sig', newline='') as f: writer = csv.writer(f) for row in saveData: writer.writerow([row['title'], row['source'], row['time'], row['summary']]) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36', 'Referer': 'https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&word=%B0%D9%B6%C8%D0%C2%CE%C5&fr=zhidao' } url = 'https://www.baidu.com/s' params = { 'ie': 'utf-8', 'medium': 0, # rtt=4 rtt=1 'rtt': 1, 'bsst': 1, 'rsv_dl': 'news_t_sk', 'cl': 2, 'tn': 'news', 'rsv_bp': 1, 'oq': '', 'rsv_btype': 't', 'f': 8, } def doSpider(keyword, sortBy = 'focus'): ''' :param keyword: :param sortBy: , :focus( ),time( ), focus :return: ''' global fileName fileName = '{}.csv'.format(keyword) if not os.path.exists(fileName): with open(fileName, 'w+', encoding='utf-8-sig', newline='') as f: writer = csv.writer(f) writer.writerow(['title', 'source', 'time', 'summary']) params['wd'] = keyword if sortBy == 'time': params['rtt'] = 4 response = requests.get(url=url, params=params, headers=headers) html = etree.HTML(response.text) dealHtml(html) total = html.xpath('//div[@id="header_top_bar"]/span/text()')[0] total = total.replace(',', '') total = int(total[7:-1]) pageNum = total // 10 for page in range(1, pageNum): print(' {}

    '.format(page)) headers['Referer'] = response.url params['pn'] = page * 10 response = requests.get(url=url, headers=headers, params=params) html = etree.HTML(response.text) dealHtml(html) sleep(randint(2, 4)) ... if __name__ == "__main__": doSpider(keyword = ' ', sortBy='focus')
    이상은python이 뉴스 포털 사이트를 기어오르는 예시의 상세한 내용입니다. 더 많은python이 뉴스 포털 사이트를 기어오르는 것에 관한 자료는 저희 다른 관련 글을 주목해 주십시오!

    좋은 웹페이지 즐겨찾기