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

yipeiwu_com5年前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 split() 函数拆分字符串将字符串转化为列的方法

函数:split() Python中有split()和os.path.split()两个函数,具体作用如下: split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字...

基于numpy中的expand_dims函数用法

基于numpy中的expand_dims函数用法

常见的一种应用场景: 条件:假设A的shape为[4, 2],B的shape为[5, 2] 目的:实现A中的每一行, 减去B中的所有行(broadcast操作)。 实现: A1 =...

python实现k-means聚类算法

python实现k-means聚类算法

k-means聚类算法 k-means是发现给定数据集的k个簇的算法,也就是将数据集聚合为k类的算法。 算法过程如下: 1)从N个文档随机选取K个文档作为质心 2)对剩余的每个文档测量其...

selenium 安装与chromedriver安装的方法步骤

selenium 安装与chromedriver安装的方法步骤

安装 selenium可以直接可以用pip安装。 pip install selenium chromedriver的安装一定要与Chrome的版本一致,不然就不起作用(不要问我是...

Python ftp上传文件

以下代码比较简单,对python实现ftp上传文件相关知识感兴趣的朋友可以参考下 #encoding=utf8 from ftplib import FTP #加载ftp模块 IP...