首页 > 解决方案 > 从 Beautiful Soup 嵌套对象中提取和存储链接

问题描述

我正在尝试从网页中抓取并保存链接。这些链接被组织为博客的 blogroll 部分中的小部件。我已经弄清楚如何创建一些 Beautifulsoup 对象的列表,但无法从该对象子集中提取链接。

我花了很多时间尝试各种类型的 find、find_all 并重新整理这些对象。

req = Request(url , headers={'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11'})
document = urlopen(req, context=ctx)
html = document.read()
soup = BeautifulSoup(html,"html.parser")



tags = soup.find_all(attrs={"class":"xoxo blogroll"})
print(type(tags))
#this is a <class 'bs4.element.ResultSet'>


count = 0
for tag in tags:
    print(type(tag))
    # this is a <class 'bs4.element.Tag'>
    print('this is tag: ', tag)#tester print

 ''' 
    this returns things like:
this is tag:  <ul class="xoxo blogroll">
<li><a href="http://blog.jaibot.com/">ANOIEAEIB</a></li>
<li><a href="http://commonsenseatheism.com/">Common Sense Atheism</a></li>
<li><a href="http://lesswrong.com">Less Wrong</a></li>
<li><a href="http://thelastpsychiatrist.com/">The Last Psychiatrist</a></li>
</ul>
<class 'bs4.element.Tag'>
this is tag:  <ul class="xoxo blogroll">
<li><a href="http://alicorn.elcenia.com/board/index.php">Alicornutopia</a></li>
<li><a href="http://unsongbook.com">Unsong</a></li>
<li><a href="https://parahumans.wordpress.com/">Worm</a></li>
</ul>

    '''

我想从每个“标签”中提取并打印所有 url,然后将它们保存到我的 sqlite3 数据库中。

标签: python-3.xweb-scrapingbeautifulsoup

解决方案


您可以尝试向其添加属性选择器,以便获得该类父母的子 href。

links = [item['href'] for item in soup.select('.blogroll [href]')]

您可能可以使用稍微快一点的

links = [item['href'] for item in soup.select('.blogroll a')]

推荐阅读