【问题标题】:get all links that avalibale in a website using python?使用python获取网站中可用的所有链接?
【发布时间】:2016-06-12 13:45:05
【问题描述】:

有没有什么方法可以使用 python 来获取网站中的所有链接,而不仅仅是网页中的链接?我尝试了这段代码,但这只给了我网页中的链接

import urllib2
import re

#connect to a URL
website = urllib2.urlopen('http://www.example.com/')

#read html code
html = website.read()

#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)

print links

【问题讨论】:

  • “网站中的所有链接不仅在网页中”是什么意思?您是指存储在 www.example.com 上的任何 html 页面中包含的每个链接吗?
  • 是的,我就是这个意思
  • 你不能那样做。您甚至可能无法访问所有 html 页面。但是,您可以递归地访问您收集的链接(如果它们也指向 www.exmaple.com 或者它们是相对链接)并从那里获取所有链接。但是,这可能不是“所有链接”,例如如果页面 example.com/jfifjfi 没有指向您的链接,您将无法访问该页面。
  • 网站链接是公开的
  • 您还可以查看scrapy,它可以满足您的所有需求。这可能是矫枉过正,你可能不会学到太多,但如果你只想完成它可能值得一看。

标签: python python-2.7 python-3.x url selenium-webdriver


【解决方案1】:

递归访问您收集的链接并删除这些页面:

import urllib2
import re

stack = ['http://www.example.com/']
results = []

while len(stack) > 0:

    url = stack.pop()
    #connect to a URL
    website = urllib2.urlopen(url)

    #read html code
    html = website.read()

    #use re.findall to get all the links
    # you should not only gather links with http/ftps but also relative links
    # you could use beautiful soup for that (if you want <a> links)
    links = re.findall('"((http|ftp)s?://.*?)"', html)

    result.extend([link in links if is_not_relative_link(link)])

    for link in links:
        if link_is_valid(link): #this function has to be written
            stack.push(link)

【讨论】:

  • if link_is_valid(link): #this function has to be written NameError: name 'link_is_valid' is not defined
  • 是的。因此我写了“#this function has to be written”作为评论。您必须检查 a) 您是否已经访问过该链接 b) 如果您甚至想访问该链接(即,它是否链接到您要访问的页面“example.com”或者它是否链接到例如维基百科) c) 如果您可以访问它(目前你正在获取 ftp 链接,我不认为 urllib2 可以处理它们?)。
猜你喜欢
  • 2013-10-04
  • 1970-01-01
  • 2023-03-03
  • 2021-08-19
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 2011-10-05
相关资源
最近更新 更多