在<div>

2024-10-01 22:37:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我对使用BeatifulSoup和python非常陌生,我在尝试在范围内获取a href时遇到了一些困难,但它没有类。。下面的代码部分来自一个phpbb论坛,我可以删除所有的href,但由于某些原因,我无法理解如何获取范围内的内容

<div class="col-md-48 post-text" data-topic="6693rw38" data-forum="2">
<br>
<br>
<a href="http://imgshare.net/img-5ba3dt3ad8a24.html" target="_blank" class="postlink" rel="nofollow"></a>
<br>
<br>
<a href="http://imgshare.net/img-5baefr1a51a49.html" target="_blank" class="postlink" rel="nofollow"></a>
<br>
<br>
<span>
    <a href="https://k2s.cc/file/5c745ce5g9193/toyota.mp4" target="_blank">https://k2s.cc/file/5c745ce5g9193/toyota.mp4</a>
</span>
<br>
<br>
<a href="http://imgshare.net/img-5ba34d1q805b8.html" target="_blank" class="postlink" rel="nofollow"></a>
<br>
<br>
<span>
    <a href="https://k2s.cc/file/b28gr283ef76e/ford.mp4" target="_blank">https://k2s.cc/file/b28gr283ef76e/ford.mp4</a>
</span>

这将为我提供a标记内的所有“href”:

url ='somephpbbforum.com'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'lxml')  

link = soup.find_all('div', class_ = 'col-md-48')

for div in link:          
    all_links = [link1['href'] for link1 in div.find_all('a')]
    print(all_links)

谢谢大家


Tags: httpsbrdivhttptargetallclassfile
1条回答
网友
1楼 · 发布于 2024-10-01 22:37:30

您可能正在寻找类似的内容(使用css选择器):

all_links = [s['href'] for s in soup.select('div.col-md-48 > a[href]')]
all_links

输出:

['http://imgshare.net/img-5ba3dt3ad8a24.html',
 'http://imgshare.net/img-5baefr1a51a49.html',
 'http://imgshare.net/img-5ba34d1q805b8.html']

编辑:

要获取这些节点的文本内容,请使用

all_links2 = [s.text for s in soup.select('div.col-md-48 > span > a[href]')]
all_links2

输出:

['https://k2s.cc/file/5c745ce5g9193/toyota.mp4',
 'https://k2s.cc/file/b28gr283ef76e/ford.mp4']

相关问题 更多 >

    热门问题