見出し画像

ウェブスクレイピングでnewsphereの記事を網羅する。

こんばんは、本職で電子部品設計をやっており、ちょっとだけ仕事持って帰ってきて、トランジスタと格闘していた。私です。本日は、
ブレンダーやるつもりでおりましたが、持って帰ってきた仕事をやってたらこんな時間になったので。昨日に引き続き、少しpythonスクリプト書いちゃおうと思います。

1.今回はニュースサイトをスクレイピング。

ドマイナーだと勝手に思ってますが、newsphereをスクレイピング。
書きがコードです。

毎回ですが、手続き型のコードしかかけてないですが、
いい加減クラス型覚えたいですわ。

import requests
import urllibfrom bs4 
import BeautifulSoup
import csvimport pandas as pdfrom urllib.request 
import urlopenimport timefrom datetime 
import datetime,timezoneimport os
import openpyxl

def Main(url):

'''Entry Point.

Args:
    url:    target url.
'''
pagenation =[]
url = url+"page/"
num = 1
while num <= 1:
    #url = "https://newsphere.jp/category/world-report/page/"
    url1 = "https://newsphere.jp/category/world-report/page/1"
    url2 = url+ str(num) +"/"
    print(str(url2)+'を解析中')
    try:
        html = urlopen(url2).read()
        soup = BeautifulSoup(html, features="html.parser")
        soup1 = soup.find(class_="pager")
        soup2 = soup1.find_all("a")
        for href in soup2:
            href = href.get("href")
            pagenation.append(href)
            time.sleep(1)
    except urllib.error.HTTPError as e:
        print("すべて確認済み")

        break
    num += 1

pagenation = sorted(set(pagenation))
print("ページ掌握完了、これよりデータ収集に移る")
news_data = [["news","link"]]

#1page目
html = urlopen(url1).read()
soup = BeautifulSoup(html, features="html.parser")
soup1 = soup.find(class_="posts posts-type4")
for element in soup1.find_all("a"):
    re = element.get("href")
    #src = element.get("src")
    link_url = urllib.parse.urljoin(url,re)   
    news = element.text
    #print(news)
    news_data.append([news,link_url])
    time.sleep(1)     

#2page目以降    
for i in pagenation:
    html = urlopen(i).read()
    soup = BeautifulSoup(html, features="html.parser")
    soup1 = soup.find(class_="posts posts-type4")
    for element in soup1.find_all("a"):
        re = element.get("href")
        #src = element.get("src")
        link_url = urllib.parse.urljoin(url,re)   
        news = element.text
        #print(news)
        news_data.append([news,link_url])
        time.sleep(1) 
        
print("データ収集完了、csvにて保存する。")        
path = r'C:\Users\xuesh\output.csv' 
path2 = r'C:\Users\xuesh\output.xlsx'

CSVファイルを開く。ファイルがなければ新規作成する。

f = open("output.csv", "w", encoding='utf-8') 
writecsv = csv.writer(f, lineterminator='\n')
writecsv.writerows(news_data)#リスト内容書き込み
f.close() # CSVファイル保存
print("csvにて保存完了、エクセルに変換用意")

重複削除

df = pd.read_csv('output.csv')#csv読み込み
df = df.drop_duplicates() 
df.to_excel('output.xlsx', encoding='utf-8',index=False)

wb = openpyxl.load_workbook(path2)
sheet = wb['Sheet1']
sheet.column_dimensions['A'].width = 100 #ピクセルではない幅
sheet.column_dimensions['B'].width = 100 #ピクセルではない幅
wb.save(path2)
time.sleep(2)  

now = datetime.now()#今日の日付
oldpath = path2 #手に入れたエクセルディレクトリ
newpath = r'C:\Users\xuesh\newsphere\{0:%Y%m%d}output.xlsx'.format(now)#移動先兼名前変更今日の日付→今回はgasで動かすフォルダ
os.rename(oldpath, newpath)
print("エクセルに変換して保存完了★")
if name == 'main':
print('準備完了')

pc名ばれたところでだからなんやねんっと最近思うようになりました。

ちなみに、アウトプットはこんな感じ

サイト上がびっちり(笑)


業務とは全く関係なかった私が、pythonを学び始めかれこれ2年弱立ちますが、私と同じような方が少しでも、pythonについて知ってもらえると幸いと思い、下記に参考記事を置いておきます。

(スクレイピングの基本的な部分について少し、下記の記事で触れています。良かったら見てもらえると幸いです。)

スクレイピングの基礎をかじりたい人向け。

python学んでみたい人向け。(pythonって何だろう?って人向け)


この記事が気に入ったらサポートをしてみませんか?