为了账号安全,请及时绑定邮箱和手机立即绑定

Python为已经定义的名称提供错误

Python为已经定义的名称提供错误

阿波罗的战车 2021-05-07 01:05:07
from selenium import webdriverfrom selenium.common.exceptions import StaleElementReferenceExceptionfrom selenium.common.exceptions import NoSuchElementExceptionpath_to_chromedriver = 'C:/Users/Admin/AppData/Local/Programs/Python/Python37-32/chromedriver.exe'browser = webdriver.Chrome(executable_path=path_to_chromedriver)browser.get('https://www.gradebeam.com/constructionresources/constructioncommunity.aspx?Category=Subs')tablebodies = browser.find_elements_by_css_selector('.rpLink.rpExpandable')print(len(tablebodies))for row in tablebodies:    CompanyName = row.find_element_by_xpath(".//*[@class='rpOut']/span[2]").text    rpslide = browser.find_element_by_class_name('rpSlide').find_elements_by_css_selector('.accountInfo')    for list in rpslide:        links = row.find_element_by_xpath(".//span[2]").text    print(CompanyName , links)上面的代码给我一个名字错误,即使链接已经被定义了.....。如果有人可以帮助将不胜感激from selenium import webdriverfrom selenium.common.exceptions import StaleElementReferenceExceptionfrom selenium.common.exceptions import NoSuchElementExceptionpath_to_chromedriver = 'C:/Users/Admin/AppData/Local/Programs/Python/Python37-32/chromedriver.exe'browser = webdriver.Chrome(executable_path=path_to_chromedriver)with open('E:\demo.txt') as f:    content = f.readlines()content = [x.strip() for x in content]with open('E:\Contractors1.csv', 'a') as f:    headers = ("Company Name,Contact Person,Address,Event_Link,PhoneNumber,Faxnumber, Website")    f.write(headers)    f.write("\n")    for link in content:        browser.get(link)        tablebodies = browser.find_elements_by_css_selector('.contentpaneopen.record-container')        for row in tablebodies:            try:                CompanyName= row.find_element_by_xpath(".//div[@class='title-container article-title pos-pagetitle item-pagetitle']/h2[1]/span[1]/a[1]/span[1]").text            except NoSuchElementException:                pass  这是另外一个类似的代码,在其中我可以打印所有内容,但网址却给了我相同的名称错误。
查看完整描述

2 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

在您的代码中-


for row in tablebodies:

    CompanyName = row.find_element_by_xpath(".//*[@class='rpOut']/span[2]").text

    rpslide = browser.find_element_by_class_name('rpSlide').find_elements_by_css_selector('.accountInfo')

    for list in rpslide:

        links = row.find_element_by_xpath(".//span[2]").text

    print(CompanyName , links)

您可以links在for list in rpslide循环范围内进行定义。但是,如果rpslide为空,links则完全不会声明。


在for循环上方声明它links = '',您的错误应该消失了。


for row in tablebodies:

    ...

    links = ''

    for list in rpslide:

        links = row.find_element_by_xpath(".//span[2]").text

    print(CompanyName , links)

另外,如果links打印为空,则需要弄清楚为什么rpslide为空,可能是-


browser.find_element_by_class_name('rpSlide').find_elements_by_css_selecto

没有找到任何东西


查看完整回答
反对 回复 2021-05-11
  • 2 回答
  • 0 关注
  • 145 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信