如何使用美丽的python 3.x提取子元素HREF



这是我的HTML代码

<div class="search_col_2">
                <h2><a href="/profile.php?id=2323232">Maahsuj akisak</a><span class="for-complete-profile">  </span>
                </h2>
<div class="search_col_2">
                <h2><a href="/profile.php?id=23232">Nunapu akisak</a><span class="for-complete-profile">  </span>
                </h2>
<div class="search_col_2">
                <h2><a href="/profile.php?id=2323332">Rahenu Kahiske</a><span class="for-complete-profile">  </span>
                </h2>

我想从中提取href值

到目前为止,我已经尝试过,但没有起作用

soupeddata = BeautifulSoup(my_html_code, "html.parser")
my_data = soupeddata.find_all("div", class_= "search_col_2")
for x in my_data:
    my_href = x.get("href")
    print(my_href)

我需要在div类中提取hrefs" search_col_2",我不想提取任何其他链接,并且还有其他链接,但我不需要它们。

即使div标签未关闭,您也可以使用以下代码获得所需的输出。

soup = BeautifulSoup(html, 'lxml')
links = [x.find('a')['href'] for x in soup.find_all('div', class_= "search_col_2")]
print(links)
# ['/profile.php?id=2323232', '/profile.php?id=23232', '/profile.php?id=2323332']

说明:

您在my_data变量中具有所有div标签。div标签没有href属性。因此,在任何div上使用.get('href')将返回None。您必须使用.find('a')div标签内找到a标签,然后获取href属性,如上所述。

最新更新