2016-03-22 13 views
1

HTMLコードbeautifulsoup使用しているとき:分割HTMLテキスト

私はそれらを個別に追加することができるように別のリスト項目として値4.5 KNおよび7.1を取得する必要があります
<td> <label class="identifier">Speed (avg./max):</label> </td> <td class="value"> <span class="block">4.5 kn<br>7.1 kn</span> </td> 

。分割したくないのですが、re.subを使って文字列を分割したかったのですが、うまくいきません。私もbrを交換するために置き換えてみましたが、動作しませんでした。誰でも洞察力を提供できますか?

Pythonコード:

def NameSearch(shipLink, mmsi, shipName): 
    from bs4 import BeautifulSoup 
    import urllib2 
    import csv 
    import re 

    values = [] 
    values.append(mmsi) 
    values.append(shipName) 
    regex = re.compile(r'[\n\r\t]') 
    i = 0 
    with open('Ship_indexname.csv', 'wb')as f: 
     writer = csv.writer(f) 
     while True: 
      try: 
       shipPage = urllib2.urlopen(shipLink, timeout=5) 
      except urllib2.URLError: 
       continue 
      except: 
       continue 
      break 
     soup = BeautifulSoup(shipPage, "html.parser") # Read the web page HTML 
     #soup.find('br').replaceWith(' ') 
     #for br in soup('br'): 
      #br.extract() 
     table = soup.find_all("table", {"id": "vessel-related"}) # Finds table with class table1 
     for mytable in table:         #Loops tables with class table1 
      table_body = mytable.find_all('tbody')     #Finds tbody section in table 
      for body in table_body: 
       rows = body.find_all('tr')    #Finds all rows 
       for tr in rows:         #Loops rows 
        cols = tr.find_all('td')     #Finds the columns 
        for td in cols:        #Loops the columns 
         checker = td.text.encode('ascii', 'ignore') 
         check = regex.sub('', checker) 
         if check == ' Speed (avg./max): ': 
          i = 1 
         elif i == 1: 
          print td.text 
          pat=re.compile('<br\s*/>') 
          print pat.sub(" ",td.text) 
          values.append(td.text.strip("\n").encode('utf-8')) #Takes the second columns value and assigns it to a list called Values 
          i = 0 
    #print values 
    return values 


NameSearch('https://www.fleetmon.com/vessels/kind-of-magic_0_3478642/','230034570','KIND OF MAGIC') 

答えて

0

は最初の "スピード(avg./max)" ラベルを見つけて.find_next()を経由して値にアクセスしてください:

from bs4 import BeautifulSoup 

data = '<td> <label class="identifier">Speed (avg./max):</label> </td> <td class="value"> <span class="block">4.5 kn<br>7.1 kn</span> </td>' 
soup = BeautifulSoup(data, "html.parser") 

label = soup.find("label", class_="identifier", text="Speed (avg./max):") 
value = label.find_next("td", class_="value").get_text(strip=True) 
print(value) # prints 4.5 kn7.1 kn 

を今、あなたは実際に抽出することができます文字列からの数字:

import re 

speed_values = re.findall(r"([0-9.]+) kn", value) 
print(speed_values) 

プリント['4.5', '7.1']

あなたはその後さらに浮かぶと別々の変数に展開するために値を変換することができます

avg_speed, max_speed = map(float, speed_values) 
+0

ありがとうございました。それは問題を解決しました。本当に正規表現を使用して素晴らしいではない、私はあなたの迅速な答えに感謝! –