我想从以下代码中提取同一个 div 类中的所有链接:
<div class='page-numbers clearfix'><span class='current'>
1</span><a href='https://www.example.com/blog/author/abc/page/2/' class='inactive'>
2</a><a href='https://www.example.com/blog/author/abc/page/3/' class='inactive'>
3</a><a href='https://www.example.com/blog/author/abc/page/4/' class='inactive'>
4</a></div>
我试过:
from bs4 import BeautifulSoup
html="<div class='page-numbers clearfix'><span class='current'>1</span><a href='https://www.example.com/blog/author/abc/page/2/' class='inactive'>2</a><a href='https://www.example.com/blog/author/abc/page/3/' class='inactive'>3</a><a href='https://www.example.com/blog/author/abc/page/4/' class='inactive'>4</a></div>
"
soup = BeautifulSoup(html, "html.parser")
for i in soup.find_all('div', {'class': 'page-numbers clearfix'}):
link= i.find('a', href=True)
print(link['href'])
但这似乎不起作用。我需要的输出是:
https://www.example.com/blog/author/abc/page/2/
https://www.example.com/blog/author/abc/page/3/
https://www.example.com/blog/author/abc/page/4/
请您参考如下方法:
您还必须使用 find_all 来查找 a 标签。下面的代码工作正常。
from bs4 import BeautifulSoup as bs
stra = """
<div class='page-numbers clearfix'><span class='current'>
1</span><a href='https://www.example.com/blog/author/abc/page/2/' class='inactive'>
2</a><a href='https://www.example.com/blog/author/abc/page/3/' class='inactive'>
3</a><a href='https://www.example.com/blog/author/abc/page/4/' class='inactive'>
4</a></div>
"""
soup = bs(stra, 'html.parser')
for i in soup.find_all('div', {'class': 'page-numbers clearfix'}):
links = i.find_all('a', href=True)
for link in links:
print(link['href'])
输出:
https://www.example.com/blog/author/abc/page/2/
https://www.example.com/blog/author/abc/page/3/
https://www.example.com/blog/author/abc/page/4/
