Skip to content

Files

Latest commit

8e2c875 · Nov 20, 2019

History

History
87 lines (53 loc) · 1.96 KB

79.md

File metadata and controls

87 lines (53 loc) · 1.96 KB

从网页中提取链接(BeautifulSoup

原文: https://pythonspot.com/extract-links-from-webpage-beautifulsoup/

Web 抓取是从网站提取数据的技术。

模块BeautifulSoup设计用于网页抓取。BeautifulSoup模块可以处理 HTML 和 XML。 它提供了用于搜索,导航和修改分析树的简单方法。

从网站获取链接

下面的示例在网页上打印所有链接:

from BeautifulSoup import BeautifulSoup
import urllib2
import re

html_page = urllib2.urlopen("https://arstechnica.com")
soup = BeautifulSoup(html_page)
for link in soup.findAll('a', attrs={'href': re.compile("^http://")}):
    print link.get('href')

它下载带有行的原始 html 代码:

html_page = urllib2.urlopen("https://arstechnica.com")

创建了BeautifulSoup对象,我们使用该对象查找所有链接:

soup = BeautifulSoup(html_page)
for link in soup.findAll('a', attrs={'href': re.compile("^http://")}):
    print link.get('href')

将网站链接提取到数组中

要将链接存储在数组中,可以使用:

from BeautifulSoup import BeautifulSoup
import urllib2
import re

html_page = urllib2.urlopen("https://arstechnica.com")
soup = BeautifulSoup(html_page)
links = []

for link in soup.findAll('a', attrs={'href': re.compile("^http://")}):
    links.append(link.get('href'))

print(links)

从网页提取链接的函数

如果您反复提取链接,则可以使用以下函数:

from BeautifulSoup import BeautifulSoup
import urllib2
import re

def getLinks(url):
    html_page = urllib2.urlopen(url)
    soup = BeautifulSoup(html_page)
    links = []

    for link in soup.findAll('a', attrs={'href': re.compile("^http://")}):
        links.append(link.get('href'))

    return links

print( getLinks("https://arstechnica.com") )