这是我的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
属性,如上所述。