2014-04-01 6 views
2

특정 웹 사이트에서 고정 된 콘텐츠를 고치고 있습니다. 아래와 같이 내용이 중첩 된 DIV 안에있다 :중첩 된 태그 웹 스크랩 핑 파이썬

<div class="table-info"> 
    <div> 
    <span>Time</span> 
     <div class="overflow-hidden"> 
      <strong>Full</strong> 
     </div> 
    </div> 
    <div> 
    <span>Branch</span> 
     <div class="overflow-hidden"> 
      <strong>IT</strong> 
     </div> 
    </div> 
    <div> 
    <span>Type</span> 
     <div class="overflow-hidden"> 
      <strong>Standard</strong> 
     </div> 
    </div> 
    <div> 
    <span>contact</span> 
     <div class="overflow-hidden"> 
      <strong>my location</strong> 
     </div> 
</div> 
</div> 

내가 사업부 내부의 강력한의 내용 만 검색 할 '오버 플로우 - 숨겨진'문자열 값 지점과 범위 내에서. 내가 사용했던 코드입니다 : 내가 필요한 콘텐츠를 검색하는 조건문을 사용할 수 있도록 내가, 주요 사업부 '테이블 정보를'내부의 모든 범위의 내용을 스크랩 한

from bs4 import BeautifulSoup 
import urllib2 
url = urllib2.urlopen("https://www.xyz.com") 
content = url.read() 
soup = BeautifulSoup(content) 
type = soup.find('div',attrs={"class":"table-info"}).findAll('span') 
print type 

. 내가 같은 범위 내의 사업부의 콘텐츠 폐기하려고한다면 :

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

사람이 나에게 범위에서 DIV의 내용을 검색하는 몇 가지 아이디어를 제공하시기 바랍니다 수 :

type = soup.find('div',attrs={"class":"table-info"}).findAll('span').find('div') 
print type 

을 내가 같은 오류가 발생합니다. 고맙습니다. 저는 python2.7을 사용하고 있습니다.

답변

1

당신이 div- "테이블 정보"내 두 번째 DIV의 콘텐츠를 원하는 것 같다 . 그러나, 당신은 당신이 접근하려고 시도하고있는 것과 관계가없는 태그를 사용하여 그것을 얻으려고합니다.

type = soup.find('div',attrs={"class":"table-info"}).findAll('span').find('div') 

은 비어있어 오류를 반환합니다.

더 나은이 시도 :

from bs4 import BeautifulSoup 
import urllib2 
url = urllib2.urlopen("https://www.xyz.com") 
content = url.read() 
soup = BeautifulSoup(content) 
type = soup.find('div',attrs={"class":"table-info"}).findAll('div') 
print type[2].find('strong').string 
+0

감사합니다, 코드는했다. 나는 그 문제를 해결하기 위해 완전히 잘못된 접근법을 따르고 있었다고 생각한다. –

0

findAll은 BS 요소 목록을 반환하고 BS 객체에는 find이 정의되어 있으므로 BS 객체 목록이 아니므로 오류가 발생합니다. 코드의 초기 부분은 괜찮 대신이 작업을 수행 :

from bs4 import BeautifulSoup 
import urllib2 

url = urllib2.urlopen("https://www.xyz.com") 
content = url.read() 
soup = BeautifulSoup(content) 

table = soup.find('div',attrs={"class":"table-info"}) 
spans = table.findAll('span') 
branch_span = span[1] 
# Do you manipulation with the branch_span 

또는

from bs4 import BeautifulSoup 
import urllib2 

url = urllib2.urlopen("https://www.xyz.com") 
content = url.read() 
soup = BeautifulSoup(content) 

table = soup.find('div',attrs={"class":"table-info"}) 
spans = table.findAll('span') 

for span in spans: 
    if span.text.lower() == 'branch': 
     # Do your manipulation