python 뉴스 포털 사이트의 예시
프로젝트 주소:
https://github.com/Python3Spiders/AllNewsSpider
어떻게 사용합니까
모든 폴더 아래의 코드는 플랫폼에 대응하는 뉴스 파충류이다
프로젝트 루트 디렉터리에 새 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이 뉴스 포털 사이트를 기어오르는 것에 관한 자료는 저희 다른 관련 글을 주목해 주십시오!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
로마 숫자를 정수로 또는 그 반대로 변환그 중 하나는 로마 숫자를 정수로 변환하는 함수를 만드는 것이었고 두 번째는 그 반대를 수행하는 함수를 만드는 것이었습니다. 문자만 포함합니다'I', 'V', 'X', 'L', 'C', 'D', 'M' ; 문자열이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.