2017-08-29 20 views
1

如何在'08 -29'和'10:15'這樣的每個日期和時間下使用循環進行換行,以便將結果從零件分離出來。如何在條件匹配編號下創建換行符?

import requests 
from bs4 import BeautifulSoup 

headers = { 
    'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"} 
all_url = 'https://www.smm.cn/' 
start_html = requests.get(all_url, 
          headers=headers) 
Soup = BeautifulSoup(start_html.text, 'lxml') 
alltd = Soup.find('div', class_='box-body').find_all('tbody') 
for td in alltd: 
    title = td.get_text() 
    j = title.split() 

for b in j: 
    print(b) 
+0

你能顯示一些你的輸入數據嗎? – Andy

+0

現在像 'SMM數據 1#電解銅 52500-52700 08-29 升貼水 (貼)100 - (貼)50 -75 11點半 洋山銅溢價(倉單) 62.00-72.00 67.00 08-29 洋山銅溢價(提單) 55.00-65.00 60.00 08-29 SMM A00鋁 16050-16090 08-29 升貼水 (貼)220 - (貼)180 -200 10:15 SMM #鉛 19200 -19350 08-29' –

+0

@KinsLau如果答案是正確的,請不要忘記加註答案並將其標記爲正確 –

回答

0

我並沒有完全得到你的意思,但如果你要打印線表示每個日期後您可以使用此代碼:如果你需要每個日期後打印線

import re 
import requests 
from bs4 import BeautifulSoup 

headers = { 
'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"} 
all_url = 'https://www.smm.cn/' 
start_html = requests.get(all_url, 
         headers=headers) 
Soup = BeautifulSoup(start_html.text, 'lxml') 
alltd = Soup.find('div', class_='box-body').find_all('tbody') 
for td in alltd: 
    title = td.get_text() 
    j = title.split() 

for b in j: 
    if re.match(r'^\d{2}(-\d{1,2})', b): 
     print(b) 
     print('\n') 
    else: 
     print(b) 

同時,各時間後,你可以用re.match(r'^\d{2}(-\d{1,2})', b) or re.match(r'^\d{1,2}(:\d{1,2})', b)替代if re.match(r'^\d{2}(-\d{1,2})', b):

如果我的回答並不能完全幫助你,也許這些鏈接可以幫助:

Using python regular expression to match times

Basic tutorials for python regular expression

祝我的朋友!