我目前正在尝试屏蔽网站以将信息放入字典中。我正在使用urllib2和BeautifulSoup。我无法弄清楚如何解析网页源信息以获得我想要的东西并将其读入字典。我想要的信息在源代码中显示为<title>Nov 24 | 8:00AM | Sole In. Peace Out. </title>
。我正在考虑使用reg表达式来读取行,将时间和日期转换为日期时间,然后解析行以将数据读入字典。字典输出应该是
[
{
"date": dateime(2010, 11, 24, 23, 59),
"title": "Sole In. Peace Out.",
}
]
当前代码:
from BeautifulSoup import BeautifulSoup
import re
import urllib2
url = 'http://events.cmich.edu/RssStudentEvents.aspx'
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
对不起文字墙,感谢您的时间和帮助!
答案 0 :(得分:1)
像这样......
titletext = soup.findAll('title')[1].string #assuming it's the second title element.. I've seen worse in html
import datetime
datetext = titletext.split("|")[0]
title = titletext.split("|")[2]
date = datetime.datetime.strptime(datetext,"%b %d").replace(year=2010)
the_final_dict = {'date':date,'title':title}
findAll()
返回搜索元素的所有实例..所以您可以像对待任何其他列表一样对待它。
那就应该这样做:)
编辑:小修补
Edit2:修复下面的评论
答案 1 :(得分:0)
您可以使用:
titleTag = soup.html.head.title
或:
soup.findAll('title')
看看这里:
答案 2 :(得分:0)
>>> soup.findAll('item')[1].title
<title>Nov 24 | 8:00AM | Sole In. Peace Out. </title>
>>> soup.findAll('item')[1].title.text
u'Nov 24 | 8:00AM | Sole In. Peace Out.'
>>> date, _, title = soup.findAll('item')[1].title.text.rpartition(' | ')
>>> date
u'Nov 24 | 8:00AM'
>>> title
u'Sole In. Peace Out.'
>>> from datetime import datetime
>>> date = datetime.strptime(date, "%b %d | %I:%M%p").replace(year=datetime.now().year)
>>> dict(date=date, title=title)
{'date': datetime.datetime(2010, 11, 24, 8, 0), 'title': u'Sole In. Peace Out.'}
请注意,这也包括一天中的时间。
然后,我想你想要所有的项目,
>>> from datetime import datetime
>>> matches = []
>>> for item in soup.findAll('item'):
... date, _, title = item.title.text.rpartition(' | ')
... matches.append(dict(date=datetime.strptime(date, '%b %d | %I:%M%p').replace(year=datetime.now().year), title=title))
...
>>> from pprint import pprint
>>> pprint(matches)
[{'date': datetime.datetime(2010, 11, 24, 8, 0),
'title': u'The Americana Indian\u2014American Indian in the American Imagination'},
{'date': datetime.datetime(2010, 11, 24, 8, 0),
'title': u'Sole In. Peace Out.'},
...
{'date': datetime.datetime(2010, 12, 8, 8, 0),
'title': u'Apply to be an FYE Mentor'}]
如果您想要更复杂的年度处理,您可以这样做。你明白了。
最后补充:生成器将是一种很好的使用方式。
from datetime import datetime
import urllib2
from BeautifulSoup import BeautifulSoup
def whatevers():
soup = BeautifulSoup(urllib2.urlopen('http://events.cmich.edu/RssStudentEvents.aspx').read())
for item in soup.findAll('item'):
date, _, title = item.title.text.rpartition(' | ')
yield dict(date=datetime.strptime(date, '%b %d | %I:%M%p').replace(year=datetime.now().year), title=title)
for match in whatevers():
pass # Use match['date'], match['title']. a namedtuple might also be neat here.