如何从多个<p>标签和 div 类中查找单个<href>



我有一个关于beautifulsoup的问题。

这就是我的div的样子。

<div class="guides__content-container">
<div class="row row-extra-small text-justify">
<div class="small-12 columns">
and then I'll have <p's> that will contain a href
<p>blalba <a href="test"></a> <a href="test1"><a></p>
<p>blalba <a href="test2"></a> <a href="test2"><a></p>
</div>
</div>
</div>

不幸的是,我别无选择,只能区分。如果每个p都有一个,我怎么才能得到一个href ?

我是这样开始的。

from bs4 import BeautifulSoup
import requests

class Scrapping:
@staticmethod
def scrappingDrones(target):
req = requests.get(target)
soup = BeautifulSoup(req.text, "html.parser")
link = soup.find({"class" : "small-12 columns"})
print(link)

if __name__ == '__main__':
url = "h"
Scrapping.scrappingDrones(url)

提前感谢!

这个可以完成这项工作。我假设您想要每个p标签的第一个链接。如果我错了,请告诉我。

divs = soup.find("div", {"class": "small-12"})
paras = divs.find_all("p")
hrefs = []
for para in paras:
anchor = para.find("a")
hrefs.append(anchor.get("href"))
print(hrefs)

输出——

['test', 'test2']

最新更新