获取源html(python)中的所有链接站点

2024-09-28 22:07:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个网页上获取所有链接,这个功能只有一个链接,但需要获取所有链接!我当然知道需要一个戒指,但我不知道用途

我需要所有的链接

def get_next_target(page):
start_link = page.find('<a href=')
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote + 1)
url = page[start_quote + 1:end_quote]
return url, end_quote

Tags: 功能url网页get链接defpagelink
3条回答

您可以使用lxml进行此操作:

 import lxml.html

 def get_all_links(page):
     document = lxml.html.parse(page)
     return document.xpath("//a")

这就是HTML解析器派上用场的地方。我推荐^{}

from bs4 import BeautifulSoup as BS
def get_next_target(page)
    soup = BS(page)
    return soup.find_all('a', href=True)
site = urllib.urlopen('http://somehwere/over/the/rainbow.html')
site_data = site.read()
for link in BeautifulSoup(site_data, parseOnlyThese=SoupStrainer('a')):
    if link.has_attr('href'):
        print(link['href'])

相关问题 更多 >