我正在尝试从IMDB网站中提取一些信息,我正在提取信息并将其写入CSV文件。当我试图找到一个不存在的元素时,它会卡住。
这是我的代码:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import os
import csv
profile = webdriver.ChromeOptions()
profile.add_experimental_option(
"prefs", {'download.default_directory': '/Users/aravind/tekie/ml-project/scrapper-opensubs/subs',
'download.prompt_for_download': False})
driver = webdriver.Chrome(
executable_path='/Users/aravind/chromedriver')
web = 'https://www.imdb.com/search/title?genres=animation&explore=title_type,genres&title_type=movie&ref_=adv_explore_rhs'
driver.get(web)
driver.implicitly_wait(2000)
with open('./movies.csv', mode='w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Movie-Title','Rating','Meta-Score','Cast','Votes','Gross'])
for page in range(0,1):
print('...crawling started')
list_of_names = driver.find_elements_by_class_name('lister-item-content')
for index in range(0,len(list_of_names)):
if list_of_names[index].find_elements_by_class_name('lister-item-header'):
title = list_of_names[index].find_elements_by_class_name(
'lister-item-header')[0].find_elements_by_tag_name('a')[0].text.strip()
else:
title="NA"
if list_of_names[index].find_elements_by_class_name('ratings-imdb-rating'):
rating = list_of_names[index].find_elements_by_class_name(
'ratings-imdb-rating')[0].text.strip()
else:
rating = "NA"
if list_of_names[index].find_elements_by_class_name('ratings-metascore'):
metaScore = list_of_names[index].find_elements_by_class_name(
'ratings-metascore')[0].find_elements_by_tag_name('span')[0].text.strip()
else:
metaScore = "NA"
if list_of_names[index].find_elements_by_tag_name('p')[2]:
cast = list_of_names[index].find_elements_by_tag_name('p')[2].text.strip()
else:
cast="NA"
if list_of_names[index].find_elements_by_class_name('sort-num_votes-visible')[0]:
votes = list_of_names[index].find_elements_by_class_name(
'sort-num_votes-visible')[0].find_elements_by_tag_name('span')[1].text.strip()
else:
votes="NA"
if list_of_names[index].find_elements_by_class_name('sort-num_votes-visible')[0]:
gross = list_of_names[index].find_elements_by_class_name(
'sort-num_votes-visible')[0].find_elements_by_tag_name('span')[4].get_attribute('data-value').strip()
else:
gross="NA"
print('done',index)
writer.writerow([title,rating,metaScore,cast,votes,gross])
我什至尝试了try except
,但没有成功。
如何不处理data_case?
答案 0 :(得分:2)
“卡住”部分的原因是driver.implicitly_wait(2000)
部分-网络驱动程序等待2000秒后才超时(大约33分钟)。
每次find_elements_by_class_name
找不到任何东西(例如,不存在)时,就会发生这种情况。