python


27、提取Soup中所有a标签

<pre><code># -*- coding:utf-8 -*- #python 2.7 #XiaoDeng #http://tieba.baidu.com/p/2460150866 #标签操作 from bs4 import BeautifulSoup import urllib.request import re #如果是网址,可以用这个办法来读取网页 #html_doc = "http://tieba.baidu.com/p/2460150866" #req = urllib.request.Request(html_doc) #webpage = urllib.request.urlopen(req) #html = webpage.read() html=""" &lt;html&gt;&lt;head&gt;&lt;title&gt;The Dormouse's story&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;p class="title" name="dromouse"&gt;&lt;b&gt;The Dormouse's story&lt;/b&gt;&lt;/p&gt; &lt;p class="story"&gt;Once upon a time there were three little sisters; and their names were &lt;a href="http://example.com/elsie" class="sister" id="xiaodeng"&gt;&lt;!-- Elsie --&gt;&lt;/a&gt;, &lt;a href="http://example.com/lacie" class="sister" id="link2"&gt;Lacie&lt;/a&gt; and &lt;a href="http://example.com/tillie" class="sister" id="link3"&gt;Tillie&lt;/a&gt;; &lt;a href="http://example.com/lacie" class="sister" id="xiaodeng"&gt;Lacie&lt;/a&gt; and they lived at the bottom of a well.&lt;/p&gt; &lt;p class="story"&gt;...&lt;/p&gt; """ soup = BeautifulSoup(html, 'html.parser') #文档对象 #查找a标签,只会查找出一个a标签 #print(soup.a)#&lt;a class="sister" href="http://example.com/elsie" id="xiaodeng"&gt;&lt;!-- Elsie --&gt;&lt;/a&gt; for k in soup.find_all('a'): print(k) print(k['class'])#查a标签的class属性 print(k['id'])#查a标签的id值 print(k['href'])#查a标签的href值 print(k.string)#查a标签的string 如果,标签&lt;a&gt;中含有其他标签,比如&lt;em&gt;..&lt;/em&gt;,此时要提取&lt;a&gt;中的数据,需要用k.get_text()</code></pre> <hr /> <p>作者:起飞并不晚 来源:CSDN 原文:<a href="https://blog.csdn.net/slhlde/article/details/81286318">https://blog.csdn.net/slhlde/article/details/81286318</a> 版权声明:本文为博主原创文章,转载请附上博文链接!</p>

页面列表

ITEM_HTML