如何提取a标签里面的 href
时间: 2023-02-12 14:57:30 浏览: 61
通过使用网页解析库如 BeautifulSoup 或 lxml,可以在 HTML 代码中查找并提取 a 标签中的 href 属性。示例代码如下:
```
from bs4 import BeautifulSoup
html_code = '<a href="https://www.example.com">example link</a>'
soup = BeautifulSoup(html_code, 'html.parser')
link = soup.find('a')
href = link['href']
print(href) # 'https://www.example.com'
```
或者
```
from lxml import etree
html_code = '<a href="https://www.example.com">example link</a>'
root = etree.HTML(html_code)
link = root.xpath("//a/@href")
print(link) # ['https://www.example.com']
```
相关问题
获取a标签里面href的标签
您可以使用BeautifulSoup库来获取a标签中的href属性值,示例代码如下所示:
```python
from bs4 import BeautifulSoup
# 假设有一个HTML文档,其中包含a标签
html_doc = """
<html>
<head>
<title>Example</title>
</head>
<body>
<a href="https://www.example.com">Example Website</a>
</body>
</html>
"""
# 使用BeautifulSoup解析HTML文档
soup = BeautifulSoup(html_doc, 'html.parser')
# 获取a标签中的href属性值
a_tag = soup.find('a')
href = a_tag['href']
print(href)
```
在上述代码中,首先使用BeautifulSoup解析HTML文档,然后使用find方法查找第一个a标签,最后使用类似字典的方式获取href属性值。
js获取所有li里面a标签的href
可以使用以下代码获取所有li里面a标签的href:
```javascript
var links = document.querySelectorAll('li a');
var hrefs = Array.prototype.map.call(links, function(link) {
return link.getAttribute('href');
});
console.log(hrefs);
```
这段代码会将所有li里面a标签的href存入一个数组中,并打印在控制台上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)