【发布时间】:2021-05-03 17:25:13
【问题描述】:
我正在尝试为谷歌搜索结果构建一个网络爬虫,并提出了 3 个场景来处理:
- 会出现一个弹出框,其中包含我需要的信息并将其提取出来 Pop Up Box
- 标题下方的文本包含信息,我将其提取出来 Text below header
- 没有有用的信息 - 我只是抓取链接 Grabbing link itself
这是我的代码,我假设使用“if”语句意味着如果 webdriver 无法检测到该元素,则意味着它将继续执行下一行代码。但是,我遇到了这个错误
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".hgKElc"}
(Session info: headless chrome=87.0.4280.66)
我特别选择了这个类名,因为我知道某些页面(在 #2 和 #3 中)会缺少它来简化流程。当一个元素未找到并转移到下一个元素时,如何让机器忽略?
我的代码:
#preparing brand name
brand_name = 'agentnateur'
sh_brand_name = brand_name.lower().replace(' ','')
#google search
wd.get('https://www.google.com/')
time.sleep(3)
subject_box = wd.find_element_by_css_selector('input[name=q]')
search_stg = '@'+ sh_brand_name +'.com contact us'
print(search_stg)
subject_box.send_keys(search_stg)
subject_box.submit()
time.sleep(5)
#extracting information -- case 1 pop up box
html = wd.page_source
if wd.find_element_by_class_name('hgKElc'):
email_address = wd.find_element_by_class_name('hgKElc')
print('yes1')
elif wd.find_element_by_class('aCOpRe').find_element_by_xpath("//*[contains(text(),'Contact')]"):
email_address = wd.find_element_by_class('aCOpRe').find_element_by_xpath("//*[contains(text(),'Contact')]")
print('yes2')
elif wd.find_element_by_class('aCOpRe').find_element_by_xpath("//*[contains(text(),'contact')]"):
email_address = wd.find_element_by_class('aCOpRe').find_element_by_xpath("//*[contains(text(),'contact')]")
print('yes3')
else:
email_address = wd.find_element_by_class('yuRUbf').find_element_by_css_selector('#rso > div:nth-child(1) > div > div.yuRUbf > a')
print(email_address)
wd.quit()
我已经尝试了 3 块 try, exception 但这不起作用,因为我需要循环继续运行以供以后的迭代。为此,理想情况下,我需要一个 continue 函数,但这在 try、异常块中不起作用。
非常感谢任何帮助!
【问题讨论】:
标签: python html selenium google-chrome webdriver