原英文标题
How can I get href links from HTML using Python?
import urllib2
website = "WEBSITE"
openwebsite = urllib2.urlopen(website)
html = getwebsite.read()
print html
到现在为止还挺好。
但我只希望纯文本HTML中的href链接。 我怎么解决这个问题?
9 个回复:
===============>>#1 票数:89 已采纳
from BeautifulSoup import BeautifulSoup
import urllib2
import re
html_page = urllib2.urlopen("")
soup = BeautifulSoup(html_page)
for link in soup.findAll('a'):
print link.get('href')
如果您只想要以http://开头的链接,您应该使用:soup.findAll('a', attrs={'href': pile("^http://")})
===============>>#2 票数:28
代码可能看起来像这样:from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, print it.
if name == "href":
print name, "=", value
parser = MyHTMLParser()
parser.feed(your_html_string)
注意: HTMLParser模块已在Python 3.0中重命名为html.parser。 将源转换为3.0时,2to3工具将自动调整导入。
===============>>#3 票数:12
看看使用漂亮的汤html解析库。
你会做这样的事情:import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html)
for link in soup.findAll("a"):
print link.get("href")
===============>>#4 票数:8
使用BS4执行此特定任务似乎有点过分。
尝试改为:website = urllib2.urlopen('http://10.123.123.5/foo_images/Repo/')
html = website.read()
files = re.findall('href="(.*tgz|.*tar.gz)"', html)
print sorted(x for x in (files))
我仅在我从一个公开文件夹中提取文件列表的场景中测试了它,该文件夹中公开了files \\文件夹,例如:
我得到了URL下的files \\ folders的排序列表
===============>>#5 票数:5
与真正的大师相比,我的答案可能很糟糕,但是使用一些简单的数学,字符串切片,查找和urllib,这个小脚本将创建一个包含链接元素的列表。 我测试谷歌和我的输出似乎是对的。 希望能帮助到你!import urllib
test = urllib.urlopen("").read()
sane = 0
needlestack = []
while sane == 0:
curpos = test.find("href")
if curpos >= 0:
testlen = len(test)
test = test[curpos:testlen]
curpos = test.find('"')
testlen = len(test)
test = test[curpos+1:testlen]
curpos = test.find('"')
needle = test[0:curpos]
if needle.startswith("http" or "www"):
needlestack.append(needle)
else:
sane = 1
for item in needlestack:
print item
===============>>#6 票数:3
使用BeautifulSoup和Python 3的请求:import requests
from bs4 import BeautifulSoup
page = requests.get('')
bs = BeautifulSoup(page.content, features='lxml')
for link in bs.findAll('a'):
print(link.get('href'))
===============>>#7 票数:2
这是@ stephen的答案的懒惰版本from urllib.request import urlopen
from itertools import chain
from html.parser import HTMLParser
class LinkParser(HTMLParser):
def reset(self):
HTMLParser.reset(self)
self.links = iter([])
def handle_starttag(self, tag, attrs):
if tag == 'a':
for name, value in attrs:
if name == 'href':
self.links = chain(self.links, [value])
def gen_links(f, parser):
encoding = f.headers.get_content_charset() or 'UTF-8'
for line in f:
parser.feed(line.decode(encoding))
yield from parser.links
像这样使用它:>>> parser = LinkParser()
>>> f = urlopen('/questions/3075550')
>>> links = gen_links(f, parser)
>>> next(links)
'//'
===============>>#8 票数:2
这是迟到的回答,但它适用于最新的python用户:from bs4 import BeautifulSoup
import requests
html_page = requests.get('').text
soup = BeautifulSoup(html_page, "lxml")
for link in soup.findAll('a'):
print(link.get('href'))
不要忘记安装“ requests ”和“ BeautifulSoup ”包以及“ lxml ”。 使用.text以及否则会抛出异常。
“ lxml ”用于删除要使用的解析器的警告。 您也可以使用“ html.parser ”,无论哪种情况适合您的情况。
===============>>#9 票数:0
这个答案类似于其他requests和BeautifulSoup ,但使用列表理解。
因为find_all()是Beautiful Soup搜索API中最流行的方法,所以你可以使用soup("a")作为soup.findAll("a")的快捷方式并使用list comprehension:import requests
from bs4 import BeautifulSoup
URL = ""
page = requests.get(URL)
soup = BeautifulSoup(page.content, features='lxml')
# Find links
all_links = [link.get("href") for link in soup("a")]
# Only external links
ext_links = [link.get("href") for link in soup("a") if "http" in link.get("href")]