1

我正在做一些需要我获取页面上所有 URL 的事情。它似乎适用于我测试过的大多数网站,例如 microsoft.com,但它只从 google.com 返回三个。以下是相关的源代码:


   import urllib
   import time
   import re
   fwcURL = "http://www.microsoft.com" #URL to read
   mylines = urllib.urlopen(fwcURL).readlines()
   print "Found URLs:"
   time.sleep(1) #Pause execution for a bit
   for item in mylines:
     if "http://" in item.lower(): #For http
       print item[item.index("http://"):].split("'")[0].split('"')[0] # Remove ' and " from the end, for example in href=
     if "https://" in item.lower(): #For https
       print item[item.index("https://"):].split("'")[0].split('"')[0] # Ditto

如果我的代码可以改进,或者如果有更好的方法可以做到这一点,请回复。提前致谢!

4

3 回答 3

3

尝试使用 Mechanize 或 BeautifulSoup 或 lxml。

通过使用 BeautifulSoup,您可以非常轻松地轻松获取所有 html/xml 内容。

import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen("some_url")
soup = BeautifulSoup(page.read())
links = soup.findAll("a")
for link in links:
    print link["href"]

BeautifulSoup非常容易学习和理解。

于 2012-06-24T04:41:25.460 回答
2

首先,HTML 不是一种常规语言,像这样的简单字符串操作在所有页面上都不起作用。您需要一个真正的 HTML 解析器。我会推荐 Lxml。然后只需在树中递归并找到所需的元素即可。

其次,有些页面可能是动态的,因此您不会在 html 源代码中找到所有内容。Google 大量使用 javascript 和 AJAX(注意它如何在不重新加载页面的情况下显示结果)。

于 2012-06-24T04:40:16.673 回答
2

我会使用 lxml 并执行以下操作:

import lxml.html

page = lxml.html.parse('http://www.microsoft.com').getroot()
anchors = page.findall('a')

值得注意的是,如果链接是动态生成的(通过 JS 或类似方式),那么您将不会以某种方式自动化浏览器。

于 2012-06-24T05:12:30.993 回答