怎么从<ul class="" data-target="area"> <li class="filter__item--level2 filter__item--aside strong" data-id="0" data-type="district"> <a href="/zufang/" rel="nofollow">不限</a> </li> <li class="filter__item--level2" data-id="23008614" data-type="district"> <a href="/zufang/dongcheng/">东城</a> </li>这段代码中把href属性值提取出来
时间: 2023-07-03 13:13:46 浏览: 66
可以使用BeautifulSoup库来解析HTML代码,并使用find_all方法选取所有的li标签,再从中提取href属性值。
例如,假设HTML代码如下:
```html
<ul class="" data-target="area">
<li class="filter__item--level2 filter__item--aside strong" data-id="0" data-type="district">
<a href="/zufang/" rel="nofollow">不限</a>
</li>
<li class="filter__item--level2" data-id="23008614" data-type="district">
<a href="/zufang/dongcheng/">东城</a>
</li>
</ul>
```
要获取所有li标签中的a标签的href属性值,可以使用以下代码:
```python
from bs4 import BeautifulSoup
html = '''
<ul class="" data-target="area">
<li class="filter__item--level2 filter__item--aside strong" data-id="0" data-type="district">
<a href="/zufang/" rel="nofollow">不限</a>
</li>
<li class="filter__item--level2" data-id="23008614" data-type="district">
<a href="/zufang/dongcheng/">东城</a>
</li>
</ul>
'''
soup = BeautifulSoup(html, 'html.parser')
lis = soup.find_all('li')
for li in lis:
a = li.find('a')
if a:
href = a['href']
print(href)
```
输出结果为:
```
/zufang/
/zufang/dongcheng/
```
其中,find_all方法用来选取所有匹配的元素,参数为标签名称字符串。在这里,我们选取所有的li标签,并遍历每个li标签。然后,使用find方法选取每个li标签下的第一个a标签,并从中提取href属性值。最后,将所有的href属性值打印出来。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![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)
<html> <head> <meta charset="utf-8" /> <title>星星国际影城</title> <script src="js/main.js" type="text/javascript"></script> </head> <body> 登录| 注册| 全国服务热线:888-8888888 < img src="images/logo.jpg" title="" alt="logo" /> 首页 影片 影城 购票 影城活动 会员服务 顾客互动 <input type="text" placeholder="搜索影片" name="search"/> <input type="button" name="btn" value="" /> < img src="images/b1.png" /> < img src="images/b2.png" /> < img src="images/b3.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)