我希望从以下 HTML 代码中提取第二个链接(即数字“2”的链接):
<div class="post-footers">
1 |<a href="index.html?page=2"> 2 </a>
|<a href="index.html?page=3"> 3 </a>
|<a href="index.html?page=4"> 4 </a>
</div>
所以我想将所有 href
输出到一个列表中,然后提取索引 1 处的元素,如下所示:
tags = soup.find("div", class_="post-footer")
links = tags.get('href')
print links[1]
但它返回错误:
newtags.get('href', None)
AttributeError: 'NoneType' object has no attribute 'get'
这意味着标签结果是空的。那么我的代码哪里出错了?
谢谢,如果有人能提供帮助:)
最佳答案
试试这个,
尝试 1
In [1]: tags = soup.find("div", class_ = "post-footers")
In [2]: links = [i.attrs['href'] for i in tags.findAll('a')]
In [3]: print links
结果 1
['index.html?page=2', 'index.html?page=3', 'index.html?page=4']
您的代码中存在拼写错误。您使用了 post-footer
而不是 post-footers
。
尝试 2
如果您将 href
用作 True
,您将得到所有这样的 a
,
In [28]: tags = soup.find("div", class_ = "post-footers")
In [31]: links = tags.find_all('a',href=True)
结果 2
[<a href="index.html?page=2"> 2 </a>,
<a href="index.html?page=3"> 3 </a>,
<a href="index.html?page=4"> 4 </a>]
关于python - 使用 BeautifulSoup 调用特定的 'div' 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41779130/