2016-09-06 6 views
2

웹 사이트에서 영양 데이터의 일부 스크래핑을 시도하고 있으며, 약간 다른 형식의 페이지가 실행될 때까지 모든 것이 지금까지 활발히 진행되고있는 것처럼 보입니다.Python - Selenium AttributeError : 목록 객체에 속성이 없습니다. find_element_by_xpath

[] 
[] 
[] 
[] 
[] 

을하지만 요소의 위치를 ​​정의 할 경우, 그것은 잘 작동 :

values = browser.find_elements_by_class_name('size-12-fl-oz' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value') 

인쇄이 반환됩니다 : 셀레늄과 같은 라인을 사용

, 빈 목록을 반환합니다 :

kcal = data.find_elements_by_xpath("(.//div[@class='size-12-fl-oz nutrition-value' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value'])[position()=1]").text 

제가 겪었던 문제는 요소가 페이지마다 다르다는 것입니다. 나는 반복한다. 따라서 div가 위치 9에 존재하지 않으면 오류가 발생합니다. 나는 try/catch을 다시 가서 내 코드를 편집 할 때

는 지금, 나는 점점 오전 :

AttributeError: 'list' object has no attribute 'find_element_by_xpath'

또는 여기

AttributeError: 'list' object has no attribute 'find_elements_by_xpath'

내 주석 지역에서 함께 코드입니다 내 테스트 앞뒤로.

import requests, bs4, urllib2, csv 
from bs4 import BeautifulSoup 
from selenium import webdriver 
from selenium.webdriver.support.ui import Select 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.common.exceptions import NoSuchElementException  

browser = webdriver.Firefox() 
... 

#Loop on URLs to get Nutritional Information from each one. 
with open('products.txt') as f: 
    for line in f: 
     url = line 
#  url = 'http://www.tapintoyourbeer.com/index.cfm?id=3' 
     browser.get(url) 
     with open("output.csv", "a") as o: 
      writeFile = csv.writer(o) 
      browser.implicitly_wait(3) 
      product_name = browser.find_element_by_tag_name('h1').text.title() #Get product name 
      size = browser.find_element_by_xpath("(//div[@class='dotted-tab'])").text #Get product size 
      data = browser.find_elements_by_xpath("//table[@class='beer-data-table']") 
#   values=[] 
#   values = browser.find_elements_by_class_name('size-12-fl-oz' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value') 
      try: 
#   values = data.find_elements_by_xpath("(.//div[@class='size-12-fl-oz nutrition-value' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value'])") 
       kcal = data.find_element_by_xpath("(.//div[@class='size-12-fl-oz nutrition-value' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value'])[position()=1]").text 
       kj = data.find_element_by_xpath("(.//div[@class='size-12-fl-oz nutrition-value' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value'])[position()=3]").text 
       fat = data.find_element_by_xpath("(.//div[@class='size-12-fl-oz nutrition-value' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value'])[position()=5]").text 
       carbs = data.find_element_by_xpath("(.//div[@class='size-12-fl-oz nutrition-value' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value'])[position()=7]").text 
       protein = data.find_element_by_xpath("(.//div[@class='size-12-fl-oz nutrition-value' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value'])[position()=9]").text 
       values = [kcal, kj, fat, carbs, protein] 
       print values 
       writeFile.writerow([product_name] + [size] + values) 
      except NoSuchElementException: 
       print("No Protein listed") 
browser.quit() 

나는 목록을 작성하고 CSV로 출력하기 위해 일찍 작업했지만, 때로는 위치 수가 잘못 나오는 경우가있었습니다.

[u'Budweiser', u'12 FL OZ', u'145.00', u'', u'', u'', u''] 
[u"Beck'S", u'12 FL OZ', u'146.00', u'610.86', u'0.00', u'10.40', u'1.80'] 
[u'Bud Light', u'12 FL OZ', u'110.00', u'460.24', u'0.00', u'6.60', u'0.90'] 
[u'Michelob Ultra', u'12 FL OZ', u'95.00', u'397.48', u'0.00', u'2.60', u'0.60'] 
[u'Stella Artois', u'100 ML', u'43.30', u'KCAL/100 ML', u'181.17', u'KJ/100 ML', u'0.00'] 

위치 9가 특정 페이지에 없을 때 문제가 시작되었습니다.

이 두통을 고치는 방법에 대한 제안이 있습니까? 다른 페이지에 대해 케이스를 설정해야합니까? & 크기입니까?

감사합니다.

답변

1

실제로 find_elements()WebElement 또는 빈 목록 중 하나를 반환합니다. 이 결과를 목록 변수 이름 data에 저장합니다.

AttributeError: 'list' object has no attribute 'find_element_by_xpath'

AttributeError: 'list' object has no attribute 'find_elements_by_xpath'

당신이 절대적으로 잘못 인 data.find_element_by_xpath() 또는 data.find_elements_by_xpath() 당신이 전화하는 이유 의 중첩 WebElementdata에 대한 목록을 찾을거야 때문에 발생합니다.

사실 find_element() 또는 find_elements()페이지 문맥 대신 또는 listWebElement상황에있는 요소를 검색하는 데 사용된다.

그래서 당신은 data 목록에서 개별 WebElement을 찾기 위해 시도해야하고 더 아래이 요소 컨텍스트를 사용 WebElement 중첩 찾을 : -

if len(data) > 0: 
    #now find desire element using index 
    individual_element = data[0] 

    #now you can find further nested single element using find_element() or list of elements using find_elements() at individual_element context 
    kcal = individual_element.find_element_by_xpath("(.//div[@class='size-12-fl-oz nutrition-value' or 'size-330-ml hide nutrition-value' or 'size-8-fl-oz nutrition-value'])[position()=1]").text 

    ---------------------------- 
    ---------------------------- 
+1

신난다. 고맙습니다. – PDGill

관련 문제