python-3.x - 找不到元素时硒卡住
问题描述
我正在尝试从 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?
解决方案
“卡住”部分的原因是driver.implicitly_wait(2000)
部分 - webdriver 在超时之前等待 2000 秒(cca 33 分钟)。
每次都会发生这种情况find_elements_by_class_name
并没有找到任何东西(例如它不存在)。
推荐阅读
- java - 在浮动操作按钮内导航
- c++ - 如何找出 gsoap 服务器接收请求的以太网接口?
- c# - 你可以在 ASP.NET Core 中使用 AuthorizationHandler 中的 AuthorizationService 吗?
- netbeans - 配置 NetBeans 以使用 JMockit 作为 javaagent 执行单个单元测试
- machine-learning - 机器学习中的训练/测试数据集
- html - 我如何使用内联 css 使 div 响应
- android - 是否可以拥有同一服务的多个实例?
- sql-server - 具有标识插入和序列的插入语句
- c# - 在c#中从字符串中删除逗号
- sql - 如何在具有两列的 postgres 中使用 ILIKE