Gemeinsame Notizen für bestimmte Personen.
Die Geschichte eines Anfängers, der Schwierigkeiten hat, eine Prüfung großer Senioren beim Web-Scraping mit Python nachzubilden.
Ich möchte "Google-Tabellen automatisch mit Python lesen und schreiben, id: temcee" reproduzieren.
"So installieren Sie PhantomJS unter Windows 7, maechabin".
Holen Sie sich laut "Google-Tabellen mit Python automatisch lesen und schreiben, id: temcee" den json mit dem gespeicherten Schlüssel. In diesem Moment,
Ein wenig umschreiben.
# coding=utf-8
import os
import json
import gspread
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from oauth2client.service_account import ServiceAccountCredentials
cred_info = json.load( open( "{Umschreiben entsprechend der Umgebung}/spread_sheet_credential.json", "r") )
SCOPE_URL = 'https://spreadsheets.google.com/feeds'
CREDENTIAL_FILE_NAME = 'spread_sheet_credential.json'
TEMPLATE_FILE_NAME = 'spread_sheet_credential_template.txt'
SHEET_PROJECT_ID = cred_info['project_id']
SHEET_PRIVATE_KEY_ID = cred_info['private_key_id']
SHEET_PRIVATE_KEY = cred_info['private_key']
SHEET_CLIENT_EMAIL = cred_info['client_email']
SHEET_CLIENT_ID = cred_info['client_id']
SHEET_CLIENT_X509_CERT_URL = cred_info['client_x509_cert_url']
def write_news(sheet, link, max_loop_count):
driver = webdriver.PhantomJS()
driver.get(link)
loop_count = 0
while loop_count < max_loop_count:
loop_count += 1
print('-------------- {}Zugriff auf die zweite Seite... --------------'.format(loop_count))
#Spread Sheet schreiben
write_techcrunch_news_elements(driver, sheet)
#Zugriff auf die nächste Seite
driver = access_to_next(driver)
def access_to_next(driver):
next = driver.find_element_by_link_text('Nächster')
#Besuchen Sie eine neue Seite, wenn eine Zeitüberschreitung auftritt
page_content = '/page/'
url = driver.current_url
splited_url_contents = url.split(page_content)
next_url = splited_url_contents[0] + page_content + str(int(splited_url_contents[1].split('/')[0]) + 1)
try:
next.click()
except Exception as e:
print('Da Timeout aufgetreten ist, wird ein neues "{}Zugreifen.'.format(next_url))
driver = webdriver.PhantomJS()
driver.get(next_url)
return driver
def write_techcrunch_news_elements(driver, sheet):
#Warten Sie bis zu 10 Sekunden und berücksichtigen Sie dabei die Zeit, die die Seite zum vollständigen Laden benötigt
driver.set_page_load_timeout(10)
title_dict = {}
blocks = driver.find_elements_by_class_name('river-block')
count = 0
for block in blocks:
count += 1
ad_contain = None
print('----- {}Der zweite Fluss-Block ist... -----'.format(count))
try:
ad_contain = block.find_element_by_class_name('ad-contain')
except Exception as e:
try:
news_title = block.find_element_by_class_name('post-title').find_element_by_tag_name('a').text
news_time = block.find_element_by_tag_name('time').get_attribute('datetime')
title_dict[news_title] = news_time
print('News No.{} title:{} date:{}'.format(count, news_title, news_time))
except Exception as e:
print('Es war ein gesponserter Artikel.'.format(count))
continue
if ad_contain is not None:
print('Es war eine Werbung.??'.format(count))
write_to_sheet(sheet, title_dict)
def write_to_sheet(sheet, dict):
keys = list(dict.keys())
values = list(dict.values())
titles = sheet.col_values(1)
start_row_num = len(titles) + 1
start_row = str(len(titles) + 1)
end_row = str(len(keys) + start_row_num)
#Schreiben Sie in die Tabelle
update_cells_with_list(sheet, 'A'+start_row, 'A'+end_row, keys, value_input_option='USER_ENTERED')
update_cells_with_list(sheet, 'B'+start_row, 'B'+end_row, values, value_input_option='USER_ENTERED')
def access_to_sheet(gid):
#Datei zum Schreiben
credential_file = open(CREDENTIAL_FILE_NAME, 'r')
credentials = ServiceAccountCredentials.from_json_keyfile_name( CREDENTIAL_FILE_NAME, SCOPE_URL)
# credentials = ServiceAccountCredentials.from_json_keyfile_name(CREDENTIAL_FILE_NAME, SCOPE_URL)
client = gspread.authorize(credentials)
return client.open_by_key(gid)
def update_cells_with_list(sheet, from_cell, to_cell, id_list, value_input_option):
cell_list = sheet.range('{}:{}'.format(from_cell, to_cell))
count_num = -1
for cell in cell_list:
count_num += 1
try:
val = id_list[count_num]
except Exception as e:
continue
if val is None:
continue
cell.value = val
print('{}Von{}Ich werde schreiben an'.format(from_cell, to_cell))
sheet.update_cells(cell_list, value_input_option=value_input_option)
#Blatt-ID des Arbeitsblatts, das Sie schreiben möchten
sheet_gid = {Tabellenkalkulations-ID}
sheet_name ={Blattname zum Schreiben in eine Tabelle}
target_link = 'https://jp.techcrunch.com/page/149/'
max_loop_count = 50
#Überprüfen Sie die oberste beschreibbare Zeilennummer der Tabelle
sheet = access_to_sheet(sheet_gid).worksheet(sheet_name)
write_news(sheet, target_link, max_loop_count)
Recommended Posts