2017-08-29 48 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

祝我的朋友!

相关问题