2016-09-15 2 views
1

난 내 코드는 아마존에서 일부 데이터를 얻으려고 :Python3, Beautifulsoup4 태그 혼란

import requests, bs4 

source_code = requests.get("https://www.amazon.com/s/ref=sr_nr_p_n_feature_keywords_0?fst=as%3Aoff&rh=n%3A2335752011%2Cn%3A%212335753011%2Cn%3A7072561011%2Cn%3A2407749011%2Cp_89%3AHuawei%2Cp_n_feature_keywords_four_browse-bin%3A6787346011&bbn=2407749011&ie=UTF8&qid=1473923594&rnid=6787345011", 
    headers={ 
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36" 
}) 
source_code.raise_for_status() 

soup = bs4.BeautifulSoup(source_code.text, 'lxml') 
mobile_div = soup.find_all("div", class_="a-row a-spacing-small") 
for mobile_name in mobile_div: 
    print(mobile_name.a.find_next("h2").string) 

가 잘 출력하지만 난

print(mobile_name.a.h2.string) 

를 사용할 때 대신 그의는 다음을 보여줍니다 오류 :

print(mobile_name.a.h2.string) 
AttributeError: 'NoneType' object has no attribute 'string' 

내 태그는 다음과 같습니다 enter image description here

아무도 내가 왜이 오류가있어 설명 할 수 있습니까?

답변

0

최초의 앵커가 반환하기 때문에입니다

<a class="a-button-text" href="/gp/help/contact-us/general-questions.html/ref=sr_hms_cs/155-8370713-5732665?browse_node_id=468556&amp;ie=UTF8&amp;qid=1473939395" role="button">contact us</a> 

그것은 더 H2 아이/자손이없는, find_nextH2에 대한 그 앵커 후에 사방에 보이는 호출 그것은이없는 그래서 경우에도 아이가 다음 아이를 찾는다. a.h2은 앵커의 하위/하위 항목을 검색하므로 위의 첫 번째 앵커는 없음을 반환합니다.

find_all_next() and find_next()

이러한 방법을 통해 어떤 태그와 문서에 뒤에 오는 문자열을 반복하는 .next_elements를 사용합니다. find_all_next() 메소드는 모든 일치하고 find_next() 첫 번째 경기가 반환을 반환

이 간단한 예를

In [34]: html = """<div> 
      <a class="a-button-text" href="/fof.com">foobar</a> 
      <h2 class="sibling"> blah</h2> 
      <div ><h2 class="nexted"> blah</h2></div> 
      </div>""" 

In [34]: soup = bs4.BeautifulSoup(html, 'lxml') 

In [35]: a = soup.div.a 
In [36]: print(a.h2) # a has no direct descendants so we get None 
None 
In [37]: a.find_next("h2") # finds the next h2 anywhere after the anchor 
Out[37]: <h2 class="sibling"> blah</h2> 


In [38]: a.find_next_siblings("h2") # finds any h2's in the tree that are siblings 
Out[38]: [<h2 class="sibling"> blah</h2>] 

In [39]: a.find_all_next("h2") # finds all h2s anywhere after 
Out[39]: [<h2 class="sibling"> blah</h2>, <h2 class="nexted"> blah</h2>] 
+0

완벽하게 일을 정리할 것을 감사합니다 : D를 – Mohib