所以lxml有一个非常方便的功能:make_links_absolute:
doc = lxml.html.fromstring(some_html_page)
doc.make_links_absolute(url_for_some_html_page)
并且文档中的所有链接现在都是绝对的。 BeautifulSoup 中是否有一个简单的等效项,或者我只需要通过 urlparse 传递它并对其进行规范化:
soup = BeautifulSoup(some_html_page)
for tag in soup.findAll('a', href=True):
url_data = urlparse(tag['href'])
if url_data[0] == "":
full_url = url_for_some_html_page + test_url
在我的回答中使用 python 提取网页上的 URL 列表的简单方法是什么? https://stackoverflow.com/questions/4139989/what-is-a-simple-way-to-extract-the-list-of-urls-on-a-webpage-using-python/4140102#4140102我在提取步骤中顺便介绍了这一点;您可以轻松地编写一个方法来对汤进行操作,而不仅仅是提取它。
from urllib.parse import urljoin
def make_links_absolute(soup, url):
for tag in soup.findAll('a', href=True):
tag['href'] = urljoin(url, tag['href'])
(Python 2:from urlparse import urljoin
.)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)