使用BeautifulSoup库可以很方便地提取网页中的链接。
如果href属性仅提供了参数而没有提供完整的链接,我们可以使用urllib.parse模块的urljoin函数将参数与原始网页链接拼接成完整的链接。然后再提取出链接。
以下是一个示例代码:
from bs4 import BeautifulSoup
from urllib.parse import urljoin
html = '''
Link 1
Link 2
'''
soup = BeautifulSoup(html, 'html.parser')
links = soup.find_all('a')
for link in links:
href = link.get('href')
full_url = urljoin('http://example.com', href)
print(full_url)
在上述代码中,我们首先使用BeautifulSoup解析了html字符串。然后使用find_all方法找到所有的a标签。接着使用get方法获取href属性的值。使用urljoin函数将href参数与原始链接'http://example.com'拼接成完整的链接。最后打印出完整的链接。
运行上述代码,输出如下:
http://example.com?id=1
http://example.com?id=2
可以看到,成功将href参数与原始链接拼接成完整的链接。