我正在从一个网站上删除日期。日期以可用的格式显示在我的浏览器中,但当我从网站提取数据字符串时,格式会发生变化?以MM/DD/YYYY格式获取日期的最简单方法是什么?在
在网站上,日期显示为:“12/05/2013 9:26 PM GMT”,当我在下面的脚本中提取它时,它显示为:“Thu Dec 05 16:26:24 EST 2013 GMT”。我只想捕捉“12/05/2013”的值
#Import libraries
import urllib2
from bs4 import BeautifulSoup
import datetime
#create output document
f = open('CarbonPrice.txt','a')
#create soup
soup = BeautifulSoup(urllib2.urlopen('https://www.theice.com/marketdata/DelayedMarkets.shtml?productId=3418&hubId=4080').read())
table = soup.find('table', {"class":"data default borderless"})
#Find and record time
try:
first_th = table.find('th')
second_th = first_th.findNext('th')
if second_th.contents[0] == 'Time':
td_tag = table.find('td', text = 'Dec13')
next_td_tag = td_tag.findNext('td')
timevar = next_td_tag.contents[0]
else:
third_th = second_th.findNext('th')
if third_th.contents[0] == 'Time':
td_tag = table.find('td', text = 'Dec13')
next_td_tag = td_tag.findNext('td')
third_td_tag = next_td_tag.findNext('td')
timevar = third_td_tag.contents[0]
else:
fourth_th = third_th.findNext('th')
if fourth_th.contents[0] == 'Time':
td_tag = table.find('td', text = 'Dec13')
next_td_tag = td_tag.findNext('td')
third_td_tag = next_td_tag.findNext('td')
fourth_td_tag = third_td_tag.findNext('td')
timevar = fourth_td_tag.contents[0]
else:
fifth_th = fourth_th.findNext('th')
if fifth_th.contents[0] == 'Time':
td_tag = table.find('td', text = 'Dec13')
next_td_tag = td_tag.findNext('td')
third_td_tag = next_td_tag.findNext('td')
fourth_td_tag = third_td_tag.findNext('td')
fifth_td_tag = fourth_td_tag.findNext('td')
timevar = fifth_td_tag.contents[0]
else:
f.write ('Error')
f.write (timevar)
except AttributeError:
f.write('Error')
f.write('\n')
f.close()
您的代码中存在各种问题。您应该尝试使用loop,这样就不需要重复相同的代码五次。在
对于BeautifulSoup,可以使用函数
find_all
,而不是find
,来查找标记的所有出现。在而且BeautifulSoup显然是以特定的格式解析时间,所以完成任务的一种方法就是解析beauthoulsoup返回的字符串。在
我把你的代码改了很多:
以下是一种方法:
相关问题 更多 >
编程相关推荐