gpt4 book ai didi

python - 如何使用 Python 从 HTML 获取 href 链接?

转载 作者:IT老高 更新时间:2023-10-28 21:35:55 25 4
gpt4 key购买 nike

import urllib2

website = "WEBSITE"
openwebsite = urllib2.urlopen(website)
html = getwebsite.read()

print html

到目前为止一切顺利。

但我只想要纯文本 HTML 中的 href 链接。我怎么解决这个问题?

最佳答案

试试 Beautifulsoup :

from BeautifulSoup import BeautifulSoup
import urllib2
import re

html_page = urllib2.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page)
for link in soup.findAll('a'):
print link.get('href')

如果您只想要以 http:// 开头的链接,您应该使用:

soup.findAll('a', attrs={'href': re.compile("^http://")})

在带有 BS4 的 Python 3 中,它应该是:

from bs4 import BeautifulSoup
import urllib.request

html_page = urllib.request.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page, "html.parser")
for link in soup.findAll('a'):
print(link.get('href'))

关于python - 如何使用 Python 从 HTML 获取 href 链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3075550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com