Python 中的屏幕抓取

发布于 2024-10-04 11:26:57 字数 601 浏览 0 评论 0原文

我目前正在尝试屏幕抓取一个网站以将信息放入字典中。我正在使用 urllib2 和 BeautifulSoup。我不知道如何解析网页源信息以获取我想要的内容并将其读入字典。我想要的信息显示为 Nov 24 |上午 8:00 |鞋底内。和平出去。源代码中的。我正在考虑使用 reg 表达式读取行,将时间和日期转换为日期时间,然后解析行以将数据读入字典中。字典输出应该类似于

[ { “日期”: dateime(2010, 11, 24, 23, 59), "title": "鞋底进场。和平出局。", } ]

当前代码:

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)

抱歉,文字墙很长,感谢您的时间和帮助!

I am currently trying to screen scrape a website to put info into a dictionary. I am using urllib2 and BeautifulSoup. I cannot figure out how to parse the web pages source info to get what I want and to read it into a dictionary. The info I want is displayed as <title>Nov 24 | 8:00AM | Sole In. Peace Out. </title> in the source code. I am thinking of using a reg expression to read in the line, convert the time and date to a datetime, and then parse the line to read the data into a dictionary. The dictionary output should be something along the lines of

[
{
"date": dateime(2010, 11, 24, 23, 59),
"title": "Sole In. Peace Out.",
}
]

Current Code:

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)

Sorry for the wall of text, and thank you for your time and help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

墨洒年华 2024-10-11 11:26:57

像这样的东西..

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:修复下面的评论

Something like this..

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() returns all instances of the search element.. so you can just treat it like any other list.

That should just about do it :)

Edit: small fix

Edit2: fix from comments below

夜空下最亮的亮点 2024-10-11 11:26:57

编辑:我没有意识到这不是一个 HTML 页面,所以看看 Chris 的更正。下面的内容适用于 HTML 页面。

您可以使用:

titleTag = soup.html.head.title

或:

soup.findAll('title')

看一下这里:

EDIT: I did not realize it's not a HTML page, so take a look at the correction by Chris. The below would work for HTML pages.

You can use:

titleTag = soup.html.head.title

or:

soup.findAll('title')

Take a look here:

情绪操控生活 2024-10-11 11:26:57
>>> 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.
>>> 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.'}

Note that that's also including the time of day.

And then, as I think you want all the items,

>>> 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'}]

If you wanted more complex year handling you could do it. You get the idea.

Final addition: a generator would be a nice way of using this.

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文