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

from selenium import webdriver

from selenium.common.exceptions import StaleElementReferenceException

from selenium.common.exceptions import NoSuchElementException

path_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 webdriver

from selenium.common.exceptions import StaleElementReferenceException

from selenium.common.exceptions import NoSuchElementException

path_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

  

这是另外一个类似的代码,在其中我可以打印所有内容,但网址却给了我相同的名称错误。


阿波罗的战车
浏览 148回答 2
2回答

繁星coding

在您的代码中-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没有找到任何东西
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python