一个<div>里面有两个一样的<ul>,两个<ul>的class和id也相同,我知道第二个<ul>里面的一个text,爬取第二个<ul>的全部超链接
时间: 2023-11-09 17:05:31 浏览: 161
可以使用BeautifulSoup库来解析HTML文档,代码如下:
```python
from bs4 import BeautifulSoup
html_doc = """
<html>
<head>
<title>Test Page</title>
</head>
<body>
<div>
<ul class="list" id="list1">
<li><a href="http://example.com/page1">Page 1</a></li>
<li><a href="http://example.com/page2">Page 2</a></li>
</ul>
<ul class="list" id="list1">
<li><a href="http://example.com/page3">Page 3</a></li>
<li><a href="http://example.com/page4">Page 4</a></li>
</ul>
</div>
</body>
</html>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# 找到第二个<ul>标签
ul_tag = soup.find_all('ul', class_='list', id='list1')[1]
# 找到全部超链接
links = ul_tag.find_all('a')
# 输出超链接
for link in links:
print(link.get('href'))
```
输出结果为:
```
http://example.com/page3
http://example.com/page4
```
阅读全文