Skip to main content
 首页 » 编程设计

python之获取页面 Python 上的所有 URL

2025年05月04日15dyllove98

我正在做的事情需要我获取页面上的所有 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 

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

请您参考如下方法:

尝试使用 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非常容易学习和理解。