我正在尝试从网页中抓取并保存链接。这些链接被组织为博客的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数据库中。
发布于 2019-04-15 23:44:45
您可以尝试向它添加一个属性选择器,这样您就可以获得该类的父类的子href。
links = [item['href'] for item in soup.select('.blogroll [href]')]您可能可以使用稍微快一点的
links = [item['href'] for item in soup.select('.blogroll a')]https://stackoverflow.com/questions/55692674
复制相似问题