2016-06-03 4 views
-2

저는 파이썬을 처음 사용하고 웹 스크 레이 핑에 관한 도움을 원합니다.웹 스크래핑 ~ 파이썬

나는 그것에 파이썬이있는 라즈베리 Pi3을 가지고 있는데, 웹 페이지에서 BeautifulSoap을 사용하여 데이터를 추출하고 타임 스탬프가있는 텍스트 파일에 쓰고 싶습니다. 그래서 파이를 24x7로 유지하고 싶습니다. 특정 시간 간격 후에 자신을 반복하므로 나중에 이러한 값을 사용하여 그래프를 만들 수 있습니다.

시작, 난>

from urllib.request import urlopen 
    from bs4 import BeautifulSoup 
    html = urlopen("https://172.30.83.14/bsnlfup/usage.php") 
    bsObj = BeautifulSoup(html.read()); 
    print(bsObj.td)" 

을 시도하고 출력은

<td align="right"> 
<a href="usage.php"><img alt="" border="0" height="152" src="images/fuph.jpg" width="100%"/></a> 

데이터가 TD 태그 안에 포함되었다거나 다른 일이었다, 그러나 많은 TD 태그에 있었다 페이지, 그래서 그것은 작동하지 않았고 내가 어떻게 txt 파일에 데이터를 작성하게 몰라요.

난 그냥

즉 내가에 78.647GB을 수출하고 싶었다 "고 (FUP - 원본)와 함께 남은 다운로드 속도"후 태그의 데이터를 내보낼 원 소스 -

<html> 
    <head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<meta http-equiv="Expires" content="0"> 
<meta http-equiv="Pragma" content="No-cache"> 
<meta http-equiv="Cache-Control" content="no-cache"> 
<meta name="keywords" content="High-Speed, Broadband, IPTV, Internet, VoIP"> 
<meta name="description" content="Leading provider of high-speed communication services."> 
<link rel="stylesheet" type="text/css" href="css/npm.css"> 
<title>BSNL BROADBAND</title> 
<script language="Javascript" type="text/javascript" src="js/npmcommon.js"></script> 
</head> 
<body onload="TINIT();" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" bgcolor="#ffffff"> 
<div class="portalheader" align="left"> 
    <table style="width: 100%;" border="0" cellspacing="0" cellpadding="0" bgcolor="white"> 
    <tr> 
     <td align="right"> 
     <a href="usage.php"><img src="images/fuph.jpg" alt="" border="0" height="152" width="100%"></a> 
     </td> 
    </tr> 
    <tr> 
     <td style="width: 100%; height: 10px; background-color: rgba(29, 117, 182, 1);"></td> 
    </tr> 
    </table> 
</div> 
<div class="serviceservlet"> 
    <table style="width: 100%;" border="0" cellpadding="0" cellspacing="0"> 
    <tbody> 
     <tr> 
     <td style="width: 165px; vertical-align: top; background-color: rgb(f, f, f);"> 
      <table border="0" cellpadding="0" cellspacing="0" width="165"> 
      <tbody> 
       <tr> 
       <td colspan="3" height="48"> 
        <br> 
       </td> 
       </tr> 
      </tbody> 
      </table> 
      <table border="0" cellpadding="0" cellspacing="0" width="165"> 
      <tbody> 
       <tr> 
       <td style="width: 10px;"> 
        <br> 
       </td> 
       </tr> 
      </tbody> 
      </table> 
     </td> 
     <td valign="top" width="100%"> 
      <table style="width: 100%; height: 204px;" border="0" cellpadding="0" cellspacing="0"> 
      <tbody> 
       <tr></tr> 
       <tr> 
       <td colspan="2"> 
        <font size="-1" face="Verdana, Arial, Helvetica, sans-serif"> 
        <br> 
        <b> 
            You are logged in as 
            '[email protected]' at 117.000.000.000. 
            <br> 
         <br> 
        </b> 
        <br> 
        <br> 
        </font> 
        <!--Display the available metered time usage stats--> 
        <table border="0" width="100%" cellpadding="0" cellspacing="0"> 
        <noscript> 
         <tr> 
         <td> 
          <a href="help.php#Java_script" target="new"> 
          <font color="#FF0000"> 
           <u>You must have JavaScript enabled in order to view usage stats.</u> 
          </font> 
          </a> 
          <br> 
          <br> 
         </td> 
         </tr> 
        </noscript> 
        <tr> 
         <td colspan="4"> 
         <font color="#0A63BF"> 
          <b> </b> 
         </font> 
         </td> 
        </tr> 
        <tr> 
         <td> 
         <i></i> 
         </td> 
        </tr> 
        </table> 
        <br> 
        <table border="0" width="100%" cellpadding="0" cellspacing="0"> 
        <noscript> 
         <tr> 
         <td> 
          <a href="help.php#Java_script" target="new"> 
          <font color="#FF0000"> 
           <u>You must have JavaScript enabled in order to view usage stats.</u> 
          </font> 
          </a> 
          <br> 
          <br> 
         </td> 
         </tr> 
        </noscript> 
        <tr> 
         <td colspan="7"> 
         <font color="#0A63BF"> 
          <b> </b> 
         </font> 
         </td> 
        </tr> 
        <tr align="left"> 
         <th>Download Remaining with High(FUP-original)Speed </th> 
        </tr> 
        <tr align="left"> 
         <td>78.647 GB</td> 
         <td> 
         <a href="top_up.php?service=HS-I-H-50MB-90GB-10MB-B-M&amp;timeMetered=false"><img name="addBytes" src="images/btn1.png" border="0" alt="[AddBytes]" title="Top up volume quota"></a> 
         </td> 
        </tr> 
        <tr height="10"> 
         <td> 
         <font color="#0A63BF"></font> 
         </td> 
        </tr> 
        </table> 
        <p> 
        <p></p> 
        </p> 
       </td> 
       <td style="width: 10px; background-color: rgb(f,f,f);"> 
        <br> 
       </td> 
       </tr> 
      </tbody> 
      </table> 
     </td> 
     </tr> 
    </tbody> 
    </table> 
</div> 
<div class="portalfooter" align="left"> 
    <td style="vertical-align: top;"> 
    <table style="width: 100%; height: 86px;" border="0" cellpadding="0" cellspacing="0"> 
     <tbody> 
     <tr> 
      <td colspan="3" rowspan="1" style="background-color: rgb(f, f, f);"> 
      <br> 
      </td> 
     </tr> 
     <tr valign="top"> 
      <td style="width: 165px; height: 10px;" border="0"> 
      <br> 
      </td> 
      <td class="npm10Text" height="10"> 
      <br> 
      <br> 
      <p align="right">2014 BSNL . All rights reserved.</p> 
      <br> 
      <br> 
      </td> 
      <td align="right" style="vertical-align: middle;"></td> 
     </tr> 
     <tr> 
      <td colspan="3" rowspan="1" style="background-color: rgba(29, 117, 182, 1);"> 
      <br> 
      </td> 
     </tr> 
     </tbody> 
    </table> 
    </td> 
</div> 
</body> 
</html> 

HTML 타임 스탬프가있는 텍스트 파일 그런 다음 시간 간격을두고 반복하고 동일한 텍스트 파일에 내 보낸 항목을 다시 추가하십시오.

+2

요요 요소에 대한 XPath를 얻으려면 Chrome 개발자 도구와 같은 것을 사용하십시오. 당신이 분석하고 싶습니다. – MattDMo

답변

1

좋아, 수프 부분은 맞지만 첫 번째 td 요소 만보고 있습니다.

원하는 정확한 것을 찾아야합니다.

tr = bsObj.find_all('tr', align='left')[1]  # find_all returns all the elements in a list 
td = tr.find('td')  # find returns only the first element in that block 
text = td.get_text() # we want the text, not the whole tag 
:이 경우 , 그것은 왼쪽 정렬로 두 번째 TR 내부의 첫번째 TD의 당신이 사용할 수있는이 경우

(거기에 도착하는 방법에는 여러 가지가 이것이 내가 쉽게 발견 하나,있다)


나는 datetime 모듈을 사용하여 타임 스탬프를 해결할 수 있다고 생각합니다. 날짜 당신이 밀리 초 않고, here

한 예로 모든 옵션을 볼 수 있습니다, 당신이 원하는 방식으로 문자열을 만들 수있는 옵션이 될 것입니다 :

now = datetime.datetime.now() 
timestamp = now.strftime('%d/%m - %Hh%M') # Note that you can add your own text with the time directives. 


가를 작성하려면 몇 가지 옵션을 출력 할 수 있습니다. 시작하여 볼 수 있습니다. here


마지막으로 X 초마다 반복하는 가장 쉬운 방법은 모든 것을 while 루프에 넣고 끝에 sleep(X)을 넣는 것입니다. 스크랩과 파일 I/O가 모두 있고 매 60 초마다 실행하려는 마법 기능을 만든 것처럼 보자.

이제 두 가지 옵션이 있습니다.

1)에 상관없이 (당신이 오류가 발생할 때 수동으로 Ctrl + C 또는 그 자체로 그것을 깰 필요가 무엇 않을 계속 무한 루프

while True: 
    do_your_magic() 
    sleep(60) 

2) 다운로드가 끝났을 때 (예 : 나머지가 0이거나 페이지가 변경된 경우) 조금 더 나은 옵션을 찾아야하지만 다운로드가 끝났을 때 페이지 소스가 어떻게 작동하는지에 따라 다릅니다. 또는, 더 직접적으로

while True: 
    done = do_your_magic() 
    if done: 
     break 
    sleep(60) 

:


while not do_your_magic(): 
    sleep(60) # This runs your magic and breaks when it's done. 
는 시도를 가지고 들어 당신은 끝났어하고 루프가 될 수있을 때 마법의 기능을 다운로드하는 동안 false를 반환하고 진정한 가질 수있다 더 많은 도움이 필요하면 지금까지 가지고있는 거리와 누락 된 부분을 알려주세요.

+0

그게 다야! 그것은 첫 번째 문제를 해결했습니다! – jayanta525

+0

도움, 나는 그것을 시간 간격 후에 반복 할 수 없습니다. datetime 모듈은 밀리 초를 출력하고 밀리 초를 제거 할 수 있습니까? 텍스트 파일 출력은 훌륭하게 작동하고, "a"를 사용하여 텍스트 파일의 하단에 출력을 추가합니다. 당신의 도움을 주셔서 감사합니다! – jayanta525

+0

자세한 정보로 업데이트하면 지금 원하는 결과를 얻을 수 있는지 살펴보십시오. – pekapa