如何用Python编写一个简单的spider?

2024-05-12 19:09:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着写这个蜘蛛已经好几个星期了,但是没有成功。用Python编写代码的最佳方法是:

1)初始url:http://www.whitecase.com/Attorneys/List.aspx?LastName=A

2)从初始url使用此正则表达式获取这些url:

hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+')

[u'/cabel', u'/jacevedo', u'/jacuna', u'/aadler', u'/zahmedani', u'/tairisto', u
/zalbert', u'/salberts', u'/aaleksandrova', u'/malhadeff', u'/nalivojvodic', u'
....

3)转到这些URL中的每一个,并使用此regex刮取学校信息

hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)'

[u'JD, ', u'University of Florida Levin College of Law, <em>magna cum laude</em> , Order of the Coif, Symposium Editor, Florida Law Review, Awards for highest grades in Comparative Constitutional History, Legal Drafting, Real Property and Sales, ', u'2007']

4)将刮掉的学校信息写入schools.csv文件

你能帮我用Python写这个蜘蛛吗?我一直想用蹩脚的语言写,但没有成功。看我以前的question

谢谢你。


Tags: of代码re信息urlselect学校class
2条回答

另外,我建议你读一下:

RegEx match open tags except XHTML self-contained tags

在尝试用正则表达式解析HTML之前。然后想想当某人的名字第一次强制页面使用unicode而不是拉丁语-1时会发生什么。

编辑:为了回答您关于在Python中使用库的问题,我建议使用Beautiful Soup,,它是一个很好的HTML解析器,并且始终支持unicode(并且对格式错误的HTML做得非常好,您将在所有地方都能找到它)。

http://www.ibm.com/developerworks/linux/library/l-spider/描述良好的IBM文章

或者

http://code.activestate.com/recipes/576551/Python食谱,代码更好,但解释更少

相关问题 更多 >