python-3.x - 从 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 数据库中。
解决方案
您可以尝试向其添加属性选择器,以便获得该类父母的子 href。
links = [item['href'] for item in soup.select('.blogroll [href]')]
您可能可以使用稍微快一点的
links = [item['href'] for item in soup.select('.blogroll a')]
推荐阅读
- python - Python Gmail IMAP 在某个日期之后
- javascript - 在另一个组件中单击时反应打开的模式窗口
- javascript - 在 Angular 中修改 json
- python-3.x - 为什么要打开 openAI 健身房?
- npm - 链接的密钥无效
- php - 让 libphonenumber 与 autoloader.php 一起工作的问题
- android - 启用 proguard 后 JNI 检测到错误导致应用程序崩溃
- http - 如何定义使用“严格动态”但包含使用“不安全内联”的回退的内容安全策略 (CSP)?
- node.js - 如何在 WebStorm 上使用远程 node_modules(容器内)?
- unity3d - 在先前保存的点云中重新定位