python提取html中的href标签,如何使用Python从HTML获取href链接?
原英文标题
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("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://")})
===============>>#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("http://www.google.com").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('http://www.website.com')
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('http://stackoverflow.com/questions/3075550')
>>> links = gen_links(f, parser)
>>> next(links)
'//stackoverflow.com'
===============>>#8 票数:2
这是迟到的回答,但它适用于最新的python用户:from bs4 import BeautifulSoup
import requests
html_page = requests.get('http://www.example.com').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 = "http://www.yourwebsite.com"
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")]
python提取html中的href标签,如何使用Python从HTML获取href链接?相关推荐
- python向mysql中添加数据标签_用python在MySQL中写入数据和添加数据
在笔者之前的博文中,已介绍了用python连接与mysql数据库的知识.包括如何安装python连接mysql的pymysql包,如何通过cusor语句将python与mysql连接起来,以及如何用p ...
- python 提取元组中的值_如何从Python元组中提取数据?
我是Python的新手.对于这些数据,我正在和Jupytier iPython合作.我试图从csv文件中提取数字数据,然后运行Sklearn.我有: 用Pandas打开并读取CSV文件 将数据设置为字 ...
- python 替换array中的值_利用Python提取视频中的字幕(文字识别)
我的CSDN博客id:qq_39783601,昵称是糖潮丽子~辣丽 从今天开始我会陆续将数据分析师相关的知识点分享在这里,包括Python.机器学习.数据库等等. 今天来分享一个Python小项目! ...
- python在json文件中查找指定数据_Python中json的取值 如何使用python提取json中指定字段的数据...
python中为什么用json有什么作用 如何用python读取json里面的值啊我爱你,所以我给了你伤害我的权力,只要我能忍受,我会一直陪伴着你,但你不能伤害我太多. 数据如下,我想要读取name. ...
- 利用python提取视频中的字幕
利用python提取视频中的字幕 `` 一.导包 import base64 import os import cv2 import requests import aip from aip impo ...
- python提取cad中的文字_[python]提取PPT中的文字(包括图片中的文字)
python是一门很强大的语言,因为有着丰富的第三方库,所以可以说Python是无所不能的. 很多人都知道,Python可以操作Excel,PDF·还有PPT,这篇文章就围绕Python提取PPT中的 ...
- Python提取PDF中的文字和图片
一,使用Python提取PDF中的文字 # 只能处理包含文本的PDF文件 #coding=utf-8 import sys import importlib importlib.reload(sys) ...
- 如何利用python提取字符串中的数字
目录 一.isdigit() 函数 二.filter() 函数 三.提取一段字符串中的数字 四.匹配指定字符串开头的数字 参考资料 一.isdigit() 函数 isdigit() 函数是检测输入字符 ...
- access数据放到list中_利用Python提取视频中的字幕(文字识别)
我的CSDN博客id:qq_39783601,昵称是糖潮丽子~辣丽 从今天开始我会陆续将数据分析师相关的知识点分享在这里,包括Python.机器学习.数据库等等. 今天来分享一个Python小项目! ...
- 举个栗子~Tableau 技巧(223):Prep 调用 Python 提取数据中的地址和经纬度
用 Tableau 做地图分析时,需要数据源中有标准的地理名称字段,或有准确的经纬度数据.但如果数据源中这两种情况都不满足,只有大概的地址信息,该怎么办呢? 这是个普遍存在的问题,需要解决:如何从不太 ...
最新文章
- jq 实现发送验证码倒计时功能
- 切记!职场邮件需注意的细节
- CentOS工作内容(二)关闭SELinux
- getchar() 和getch()
- 【蓝桥杯】基础练习 十六进制转八进制
- 欢迎各位大佬,哥哥姐姐 打赏,
- 数学 余式定理 简介
- java 域账户登录失败_域用户登陆,错误:无法登录到你的账户,通常可以通过从你的账户注销,然后重新登录来解决此问题...
- 霸气:马云要让大部分药厂消失!
- 站长技术导航二开美化网站源码 网站提交自动秒收录
- 汇编实验四——扬声器程序设计
- Kubernetes基础1
- win10右键卡顿原因_win10系统右键卡顿的解决方法
- 什么是java变量,java变量的定义
- 爱奇艺发布iQUT未来影院,移动观影千亿新市场初露端倪
- 西安中科创达面试(java方向)
- Python的整数与浮点数计算
- AD20——批量快速放置元件管脚
- Centos7配置dhcp服务
- stm32F407-------RTC实时时钟