2011-07-03 97 views
1

在蟒蛇我抄一个网页,并希望得到的<a href=Python字符串范围(解析HTML)

所有出现我使用的urllib2和我的设置如下:

import urllib2 
response = urllib2.urlopen("http://python.org") 
html = response.read() 

会是什么处理这个任务的最好方法是什么?我将如何从已存储整个网页的变量中选择一系列字符串文本?

+0

+1 *不*提的正则表达式:-) – Johnsyweb

+0

是美丽的汤还能够发现电子邮件地址,电话号码等的? – nobody

+0

呃 - 哦!你想达到什么目的? – Johnsyweb

回答

4

对于在Python中解析HTML,我更喜欢BeautifulSoup。这是假设你想要找到链接,而不仅仅是文字<a href=,你可以很容易地通过字符串搜索。

+0

谢谢,这将使它更容易;) – nobody

+1

哇; BeautifulSoup是惊人的 – nobody

+0

没问题。高兴地帮助:) –

1

听起来像你需要一个HTML解析器。看看Beautiful Soup。我不会使用正则表达式,它会非常混乱,并且容易出错。

+1

感谢,这将使它更容易;) – nobody

0

你可以例如使用正则表达式匹配HTML链接或子类Python的内建SGML解析器:

from sgmllib import SGMLParser 

class URLExtractor(SGMLParser): 
    def reset(self): 
     SGMLParser.reset(self) 
     self.urls = [] 

    def start_a(self, attrs): 
     for name, value in attrs: 
      if name == 'href': 
       self.urls.append(value) 

你会使用它这样的:

extractor = URLExtractor() 
extractor.feed(html) 
print extractor.urls 
3

这是Beautiful Soup工作当然:

>>> from BeautifulSoup import BeautifulSoup 
>>> import urllib2 
>>> page = urllib2.urlopen('http://stackoverflow.com/') 
>>> soup = BeautifulSoup(page) 
>>> links = soup.html.body.findAll('a', limit=10) 
>>> for i, link in enumerate(links): 
...  print i, ':', link.text, ' -- ', link['href'] 
... 
0 : Stack Exchange -- http://stackexchange.com 
1 : log in -- /users/login 
2 : blog -- http://blog.stackoverflow.com 
3 : careers -- http://careers.stackoverflow.com 
4 : chat -- http://chat.stackoverflow.com 
5 : meta -- http://meta.stackoverflow.com 
6 : about -- /about 
7 : faq -- /faq 
8 : Stack Overflow --/
9 : Questions -- /questions 

该frontpag上有很多链接Ë;我已经将输出限制在前十位!

0

美丽的汤的另一个+1。也就是说,如果你真的想要一个简单的解析器,你可以使用正则表达式搜索。

>>> import urllib2 
>>> response = urllib2.urlopen("http://python.org") 
>>> html = response.read() 

>>> import re 
>>> re.findall("<a[^>]*href=[^>]*>", html) 

注意:更新正则表达式来进行更精确的基于评论

+1
+0

当然 - 上面的例子大部分是第一遍。我相信我错过了一些边缘情况。你可以做re.findall(“”* href = [^>] *>“,html)来更准确。再说一遍 - 无论如何,美丽的汤可能是更好的解决方案。 – shreddd