python提取页面内url列表的方法

yipeiwu_com6年前Python基础

本文实例讲述了python提取页面内url列表的方法。分享给大家供大家参考。具体实现方法如下:

from bs4 import BeautifulSoup
import time,re,urllib2
t=time.time()
websiteurls={}
def scanpage(url):
  websiteurl=url
  t=time.time()
  n=0
  html=urllib2.urlopen(websiteurl).read()
  soup=BeautifulSoup(html)
  pageurls=[]
  Upageurls={}
  pageurls=soup.find_all("a",href=True)
  for links in pageurls:
    if websiteurl in links.get("href") and links.get("href") not in Upageurls and links.get("href") not in websiteurls:
      Upageurls[links.get("href")]=0
  for links in Upageurls.keys():
    try:
      urllib2.urlopen(links).getcode()
    except:
      print "connect failed"
    else:
      t2=time.time()
      Upageurls[links]=urllib2.urlopen(links).getcode()
      print n,
      print links,
      print Upageurls[links]
      t1=time.time()
      print t1-t2
    n+=1
  print ("total is "+repr(n)+" links")
  print time.time()-t
scanpage("http://news.163.com/")

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python语言快速上手学习方法

最近在学习Python,后面搞机器人项目需要用到,所以要快速上手,我使用的是PyCharm这个IDE,看起来就舒服,学习起来就有劲啦,作为一名有工作经验的老司机,我学习编程语言的方法不会...

Python流行ORM框架sqlalchemy安装与使用教程

本文实例讲述了Python流行ORM框架sqlalchemy安装与使用。分享给大家供大家参考,具体如下: 安装 http://docs.sqlalchemy.org/ 1、安装 #进...

Python在Matplotlib图中显示中文字体的操作方法

1.    说明 本篇主要针对在Ubuntu系统中,matplotlib显示不了中文的问题,尤其是在无法安装系统字体的情况下,解决Python绘图时中文显示...

Python基于identicon库创建类似Github上用的头像功能

本文实例讲述了Python基于identicon库创建类似Github上用的头像功能。分享给大家供大家参考,具体如下: Identicon在很多大型IT网站上可以见到,比如Github,...

pytorch 自定义数据集加载方法

pytorch 官网给出的例子中都是使用了已经定义好的特殊数据集接口来加载数据,而且其使用的数据都是官方给出的数据。如果我们有自己收集的数据集,如何用来训练网络呢?此时需要我们自己定义好...