원하는 목록 루프 돌리기, 각각 항목으로 결과값 저장하기..

조회수 679회

안녕하세요. 파이썬 어린이 입니다. 궁금한 부분이 있어 여쭤봅니다 피싱사이트 검사 프로그램을 만들고 있는데요,

  1. 현재는 URL 입력을 String 입력하는 방식인데요, 한번에 여러개의 사이트를 돌리고 싶어서 하기와 같이 진행을 하고 싶은데,

" A.com 입력시 프로그램 1회 실행 후 A.com.txt 파일명으로 파일저장 후 B.com 작업 이어서 진행 " 이런식 으로 변경하고 싶습니다

더 자세히 말씀드리면

domain.txt 이란 파일에 https://www.google.com/ https://www.youtube.com/ https://www.yahoo.co.jp/ https://www.amazon.co.jp/ https://www.google.co.jp/ https://twitter.com/ https://www.facebook.com/ https://www.wikipedia.org/ 이런식으로 있다고 할 경우, 한 사이트의 모든 작업이 완료되면 다음 사이트 작업 어떻게 변경을 해야 할까요 ..?

  1. 입력값(URL)에 맞춰서 URL(입력값)+image_list.txt 이런식으로 텍스트 파일을 만들고, 안에 출력값(URL)을 넣고 싶은데, 어떻게 해야 할까요 ㅜ url 입력 변수를 그대로 넣으니 오류가 나네요.

그럼 코드입니다

import sys
import time
#import MeCab
import requests
import pandas as pd
from bs4 import BeautifulSoup
#import chromedriver_binary
from selenium import webdriver
import re
import chromedriver_binary
#import firefox_screenshot
from PIL import Image

url=raw_input("Enter the string value : ")#input the url from the user
Firefoxbrowser = webdriver.Firefox()
Firefoxbrowser.get(url)#to open the webpage
Firefoxbrowser.save_screenshot('/Users/eunhyulkim/pshing/test.png')
Firefoxbrowser.quit()

p = re.compile(r"(?:https?|ftps?)://([A-Za-z0-9-]{1,63}\.)*([A-Za-z0-9-]{1,63}\.)([A-Za-z0-9-]{1,63})/?[A-Za-z0-9.\-?=#%/]*")
z = re.compile(r"(?:https?|ftps?)://([A-Za-z0-9-]{1,63}\.)*(?:(com)|(org)|([A-Za-z0-9-]{1,63}\.)([A-Za-z0-9-]{1,63}))/?[A-Za-z0-9.\-?=#%/]*")


def re(url, num):
    if num == 0:
        m = p.match(url)
    else:
        m = z.match(url)
    if m:
        return "".join(map(str, m.groups('')))

def google_image_search(url):
    options = webdriver.ChromeOptions()
    #options.add_argument('--headless')
    driver = webdriver.Chrome('/usr/local/bin/chromedriver')
    #driver = webdriver.Chrome('/usr/local/lib/python2.7/dist-packages/chromedriver_binary', options=options)
    #driver = webdriver.Chrome()
    driver.get('https://www.google.co.jp/imghp?hl=ja')
    time.sleep(5)
    driver.find_element_by_class_name('BwoPOe').click()
    time.sleep(0.5)
    print('get')
    #driver.find_element_by_class_name('bd qbtbtxt qbclr').click
    print('quit')
    elm = driver.find_element_by_id('qbfile')
    elm.send_keys('/Users/eunhyulkim/pshing/test.png')
    time.sleep(2)

    data = driver.page_source.encode('utf-8')
    html = BeautifulSoup(data, "html.parser")

    title_lst = []
    url_lst = []

    for diva in html.find_all("div"):
        line = diva.get('class')
        line2 = ''
        #print(line)
        if line != None:
            line2 = line[0].decode('unicode-escape')
        else:
            continue
        try:
            #print(diva)
            element = diva.find_element_by_class_name("iUh30")
        except TypeError:
            pass
        #print(element)
        if line2 == "r":
            #print(diva)

            for tit in diva.find_all("h3"):
                try:
                    print(tit.text)
                    title_lst.append(tit.text)
                except TypeError:
                    pass
            for link in diva.find_all("a"):
                line5 = link.get('href')
                print(line5)

                try:
                    url_lst.append(line5)
                except TypeError:
                    pass

                break

    screen = url + 'image_list.txt'
    fh = open(screen, 'w')
    for g in range(0, len(title_lst)):
        print(type(title_lst[g]))
        print(type(url_lst[g]))
        print(type(title_lst[g].encode('utf-8')))
        title = title_lst[g].encode('utf-8')
        url = url_lst[g].encode('utf-8')
        domein1 = re(url, 0)
        domein2 = re(url, 1)
        fh.write(title + ",,," + url + ",,," + domein1 + ",,," + domein2 + "\n")

    fh.close()

    driver.quit()

google_image_search('/url/')

잘 부탁드립니다 ㅜ

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 아래코드 참고하세요. domain.txt 파일에서 각 라인별로 작업하는 샘플입니다.

    • domain.txt
    https://www.google.com
    https://www.youtube.com
    https://www.yahoo.co.jp
    https://www.amazon.co.jp
    https://www.google.co.jp
    https://twitter.com 
    https://www.facebook.com
    https://www.wikipedia.org
    
    import re
    
    def do_action(domain):
        domain = re.findall(r'https?://([A-Za-z_0-9.-]+.[a-z])', domain)[0]  # https:// http:// 을 제거한다.
        with open(f'{domain}_image_list.txt', 'w') as f:
            f.write('anything...')
    
    with open('domain.txt', 'r') as f:
        for domain in f:
            do_action(domain.rstrip())   # \n 제거후 도메인 대입
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)